Helper
Rails Generate Helper (rails g helper
) is the generator for ActionView helpers. Rails automatically includes helper methods into your views, giving you a place to put shared view logic.
Rails ships with tons of built-in helpers — you're probably familiar with Rails helper methods like #time_ago_in_words
, #image_tag
and #button_to
.
You can use the Rails helper generator to create your own helper methods; The generator will create a new module in app/helpers
for you, which is automatically included into all your views —
❯ rails g helper example --no-helper-specs
create app/helpers/example_helper.rb
# app/helpers/example_helper.rb
module ExampleHelper
end
Despite writing your helpers inside modules like ExampleHelper
, you call the methods directly; The modules just help you organize your helper methods.
To use your helper methods outside your views, you access them on the helpers
object (Rails 5+). For example, you would access a helper method inside a controller like this —
class HomeController
def index
# "about 1 hour"
helpers.time_ago_in_words(1.hour.ago)
end
end
rails g helper
rails g helper
Helper name
Generator Options
Runtime Options
❯ rails g helper Usage: rails generate helper NAME [options] Options: [--skip-namespace], [--no-skip-namespace] # Skip namespace (affects only isolated engines) [--skip-collision-check], [--no-skip-collision-check] # Skip collision check -t, [--test-framework=NAME] # Test framework to be invoked # Default: Runtime options: -f, [--force] # Overwrite files that already exist -p, [--pretend], [--no-pretend] # Run but do not make any changes -q, [--quiet], [--no-quiet] # Suppress status output -s, [--skip], [--no-skip] # Skip files that already exist
Description: Generates a new helper. Pass the helper name, either CamelCased or under_scored. To create a helper within a module, specify the helper name as a path like 'parent_module/helper_name'. Example: `bin/rails generate helper CreditCard` Credit card helper. Helper: app/helpers/credit_card_helper.rb