Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RubyOnRails: How do I use helper methods in Rails Console?

Probably something wrong with my setup:

irb(main):001:0> truncate("Once upon a time in a world far far away", :length => 17)
NoMethodError: undefined method `truncate' for main:Object
        from (irb):1
        from /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:47:in `start'
        from /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands/console.rb:8:in `start'
        from /usr/lib64/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:41:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rails:6:in `<main>'

Looks like I cannot use any text helpers (both in irb and rails console).

What should I check?

like image 709
TopperH Avatar asked Oct 17 '12 20:10

TopperH


People also ask

Can we use helper method in controller Rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

What are helper methods?

A helper method is a small utility function that can be used to extract logic from views and controllers, keeping them lean. Views should never have logic because they're meant to display HTML. In addition, there's no way to test view logic, but if we extract this logic into methods it can then be tested.


2 Answers

The Rails Console exposes the helper methods through the helper variable. Therefore, please, use this instead:

helper.truncate("Once upon a time in a world far far away", :length => 17)

for more, please read this article on 37signals.com

like image 98
Stoic Avatar answered Oct 06 '22 18:10

Stoic


type following line into your rails console

include ActionView::Helpers

now your helpers are accessible during the entire rails console session and you can continue like…

truncate("Once upon a time in a world far far away", :length => 17)

like image 27
netznarkose Avatar answered Oct 06 '22 19:10

netznarkose