How to invoke method in a controller in a ruby file or rake script file
-
02-01-2020 - |
Question
If I have a method in a controller,
For example, I want call the show
method in a script without opening the webpages.
Is it possible to do it ?
def index
@joseph_memos = JosephMemo.all
@joseph_memo = JosephMemo.new
end
# GET /joseph_memos/1
# GET /joseph_memos/1.json
def show
binding.pry
end
Solution
This should work in Rails console, run rails c
and type the following to test.
app.get('/joseph_memos/1')
output = app.html_document.root.to_s
But, if you also want to turn into rake task. Create the lib/tasks/actions.rake in your rails app. And add the following lines.
namespace :actions do
desc "test show action"
task :show, [:id] => :environment do |task, args|
app = ActionDispatch::Integration::Session.new(Rails.application)
app.get("/joseph_memos/#{args[:id]}")
puts app.html_document.root.to_s
end
end
Then run, rake actions:show[1]
to see the result.
Here is the result that works (that is, bundle exec rake "actions:show[1]"
on zsh)
$bundle exec rake "actions:show[1]"
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
<link data-turbolinks-track="true" href="/assets/joseph_memos.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/scaffolds.css?body=1" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/assets/application.css?body=1" media="all" rel="stylesheet" />
<script data-turbolinks-track="true" src="/assets/jquery.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/jquery_ujs.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/turbolinks.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/joseph_memos.js?body=1"></script>
<script data-turbolinks-track="true" src="/assets/application.js?body=1"></script>
<meta content="authenticity_token" name="csrf-param" />
<meta content="lZqYRkVfhZUhMK8EQIRsdoX2l4IpTPPhHKB44DSaq7s=" name="csrf-token" />
</head>
<body>
<p id="notice"></p>
<a href="/joseph_memos/1/edit">Edit</a> |
<a href="/joseph_memos">Back</a>
</body>
</html>
More examples: https://github.com/henrik/remit/blob/master/lib/tasks/dev_events.rake
Hope this is useful for you.
OTHER TIPS
i think it's very much possible but implementing it won't be worth it. An alternative solution would be to create a service class that you can call in the show action and you should also be able to use the same class outside of the controller.
def show
MyShowActionHandler.new(params).do_something
end
class MyShowActionHandler
def initialize(params)
@params = params
end
end
Then just call MyShowActionHandler
in a script and it should work as long as you load the rails environment.