Accessing helpers and paths in Ruby On Rails console
You can access path/url in two ways:
1) using app
, for instance:
app.game_path(1)
2) including Rails.application.routes.url_helpers
, for instance:
include Rails.application.routes.url_helpers
game_path(1)
both will result with a string => "/games/1"
The above knowledge will be handy if you are going to use helpers with paths.
Accessing helpers in rails console
The easiest way to do this is through helper
object, for instance
helper.number_to_currency(100)
=> "$100.00"
helper.link_to("test", app.game_path(1), method: :get)
=>
"<a data-method=\"get\" href=\"/games/1\">test</a>"
The nice thing about is that you can use your helpers in the same fashion:
Some real life usage:
module EventsHelper
def event_form_header(event)
content_tag :h2, class: 'text-center pull-left' do
if event.game
"#{event.category.capitalize} for #{event.game.title}"
else
"Global #{event.category.capitalize}"
end
end
end
end
=>
"<h2 class=\"text-center pull-left\">Cash_ladder for Gentleman Test Game</h2>"
Unfortunately, if you want to use your helper in console and this helper uses path inside you will have to first include Rails.application.routes.url_helpers
in this helper (which is of course not needed if you are using it in views)
module PlayerHelper
include Rails.application.routes.url_helpers
def user_player_info(player)
if player.user.removed_by_user?
'User removed his account'
else
content_tag(:div, player.user.username) +
link_to(player.reference,
game_player_path(player.game, player),
class: 'highlight')
end
end
end
helper.user_player_info(Player.last)
=>
"<div>Varian</div><a class=\"highlight\" href=\"/games/2-hots/players/3\">Thrall</a>"
Tweet