Accessing Helper modules in rails

>
Methods defined in Helper modules can directly accessed in rails views because this is what they are pretended for but we often come across with situations where we wanted to use some helper methods in controllers, views, models and mailers and obvious we don’t want to repeat same lines of code everywhere which also rail does not permit. forgotten DRY? Oh then how to do achieve same without violating rails principle.

Certainly there are ways to do this ..

1. Helper methods all the time for views
class ApplicationController < ActionController::Base
helper :all# include all helpers, all the time for views
end

2. Controller methods in views
class ApplicationController < ActionController::Base
helper_method :current_store
#now controller_method can be accessed in views
end

2. Helper methods in controller
class ApplicationController < ActionController::Base
include ActionView::Helpers::ApplicationHelper
end

3. Helper methods in model
class Student < ActiveRecord::Base
include ActionView::Helpers::ApplicationHelper
end

4. Helper methods in mailer
class Notifier < ActionMailer::Base
add_template_helper(ApplicationHelper)
#...
end

Advertisements

About sandipransing

Web Developer #ruby #rails #JS
This entry was posted in Ruby on Rails. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s