Jak wywołać metody controller/view z konsoli w Rails?
Kiedy Ładuję script/console
, kilka razy chcę grać z wyjściem kontrolera lub metody pomocniczej widoku.
Są sposoby na:
- symulować żądanie?
- wywołanie metod z instancji kontrolera na wspomniane żądanie?
- testować metody pomocnicze, albo poprzez wspomnianą instancję kontrolera, albo w inny sposób?
13 answers
Aby wywołać helpers, użyj obiektu helper
:
$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"
Jeśli chcesz użyć helpera, który nie jest domyślnie dołączony (powiedzmy, ponieważ usunąłeś helper :all
z ApplicationController
), po prostu dołącz ten helper.
>> include BogusHelper
>> helper.bogus
=> "bogus output"
Co do obsługi kontrolerów , to cytuję Nicka ODPOWIEDŹ:
> app.get '/posts/1' > response = app.response # you now have a rails response object much like the integration tests > response.body # get you the HTML > response.cookies # hash of the cookies # etc, etc
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 10:31:37
Łatwy sposób wywołania akcji kontrolera ze skryptu / konsoli i przeglądania / manipulowania obiektem odpowiedzi to:
> app.get '/posts/1'
> response = app.response
# you now have a rails response object much like the integration tests
> response.body # get you the HTML
> response.cookies # hash of the cookies
# etc, etc
Obiekt app jest instancją ActionController::Integration:: Session
To działa u mnie przy użyciu Rails 2.1 i 2.3, nie próbowałem wcześniejszych wersji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-01 20:57:41
Jeśli chcesz przetestować z konsoli (testowane na Rails 3.1 i 4.1):
Wywołanie Akcji Kontrolera:
app.get '/'
app.response
app.response.headers # => { "Content-Type"=>"text/html", ... }
app.response.body # => "<!DOCTYPE html>\n<html>\n\n<head>\n..."
Metody ApplicationController:
foo = ActionController::Base::ApplicationController.new
foo.public_methods(true||false).sort
foo.some_method
Pomocnicy Trasy:
app.myresource_path # => "/myresource"
app.myresource_url # => "http://www.example.com/myresource"
Pomocnicy Widoku:
foo = ActionView::Base.new
foo.javascript_include_tag 'myscript' #=> "<script src=\"/javascripts/myscript.js\"></script>"
helper.link_to "foo", "bar" #=> "<a href=\"bar\">foo</a>"
ActionController::Base.helpers.image_tag('logo.png') #=> "<img alt=\"Logo\" src=\"/images/logo.png\" />"
Render:
views = Rails::Application::Configuration.new(Rails.root).paths["app/views"]
views_helper = ActionView::Base.new views
views_helper.render 'myview/mytemplate'
views_helper.render file: 'myview/_mypartial', locals: {my_var: "display:block;"}
views_helper.assets_prefix #=> '/assets'
Metody ActiveSupport:
require 'active_support/all'
1.week.ago
=> 2013-08-31 10:07:26 -0300
a = {'a'=>123}
a.symbolize_keys
=> {:a=>123}
Libiąż:
> require 'my_utils'
=> true
> include MyUtils
=> Object
> MyUtils.say "hi"
evaluate: hi
=> true
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-29 13:31:28
Jest jeden sposób, aby to zrobić przez konsolę:
>> foo = ActionView::Base.new
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>
>> foo.extend YourHelperModule
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>
>> foo.your_helper_method(args)
=> "<html>created by your helper</html>"
Utworzenie nowej instancji ActionView::Base
daje dostęp do zwykłych metod widoku, których prawdopodobnie używa twój pomocnik. Następnie rozszerzenie YourHelperModule
miesza swoje metody z obiektem, umożliwiając wyświetlenie ich wartości zwrotnych.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-30 00:19:53
Innym sposobem jest użycie debuggera rails. Jest poradnik Rails o debugowaniu na http://guides.rubyonrails.org/debugging_rails_applications.html
Zasadniczo uruchom serwer z opcją-u:
./script/server -u
A następnie wstaw do skryptu punkt przerwania, w którym chcesz mieć dostęp do kontrolerów / helperów / itp..
class EventsController < ApplicationController
def index
debugger
end
end
A gdy wyślesz żądanie i naciśniesz tę część kodu, konsola serwera zwróci monit, w którym możesz następnie wykonuj żądania, przeglądaj obiekty, itp.. z wiersza polecenia. Po zakończeniu, po prostu wpisz 'cont', aby kontynuować wykonywanie. Istnieją również opcje rozszerzonego debugowania, ale to powinno przynajmniej zacząć.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-27 03:30:23
If method is POST
method then
app.post 'controller/action?parameter1=value1¶meter2=value2'
[tutaj parametry będą zgodne z Twoją stosowalnością]
Else if it is GET
method then
app.get 'controller/action'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-29 16:22:06
Możesz uzyskać dostęp do swoich metod w konsoli Rails, jak poniżej
controller.method_name
helper.method_name
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-30 11:22:39
Oto jak wykonać uwierzytelnione żądanie POST, używając rafinerii jako przykładu:
# Start Rails console
rails console
# Get the login form
app.get '/community_members/sign_in'
# View the session
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the login request.
# Log in from the console to create a session
app.post '/community_members/login', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "refinery_user[login]"=>'chloe', 'refinery_user[password]'=>'test'}
# View the session to verify CSRF token is the same
app.session.to_hash
# Copy the CSRF token "_csrf_token" and place it in the request. It's best to edit this in Notepad++
app.post '/refinery/blog/posts', {"authenticity_token"=>"gT7G17RNFaWUDLC6PJGapwHk/OEyYfI1V8yrlg0lHpM=", "switch_locale"=>"en", "post"=>{"title"=>"Test", "homepage"=>"0", "featured"=>"0", "magazine"=>"0", "refinery_category_ids"=>["1282"], "body"=>"Tests do a body good.", "custom_teaser"=>"", "draft"=>"0", "tag_list"=>"", "published_at(1i)"=>"2014", "published_at(2i)"=>"5", "published_at(3i)"=>"27", "published_at(4i)"=>"21", "published_at(5i)"=>"20", "custom_url"=>"", "source_url_title"=>"", "source_url"=>"", "user_id"=>"56", "browser_title"=>"", "meta_description"=>""}, "continue_editing"=>"false", "locale"=>:en}
Mogą się one również okazać przydatne, Jeśli pojawi się błąd:
app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-28 21:40:15
W rails 3 Spróbuj tego:
session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body
Body będzie zawierać HTML adresu url.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:50
Wcześniejsze odpowiedzi wywołują helpery, ale poniższe pomogą w wywołaniu metod kontrolera. Używałem tego na rails 2.3.2.
Najpierw dodaj poniższy kod do swojego .plik irbrc (który może znajdować się w katalogu domowym)
class Object
def request(options = {})
url=app.url_for(options)
app.get(url)
puts app.html_document.root.to_s
end
end
Następnie w konsoli rails możesz wpisać coś takiego...
request(:controller => :show, :action => :show_frontpage)
...a html zostanie wrzucony do konsoli.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-07-25 23:58:25
Jednym z możliwych sposobów testowania metod Helpera w konsoli rails jest
Struct.new(:t).extend(YourHelper).your_method(*arg)
I do reload i do
reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-15 08:57:31
Wewnątrz dowolnej akcji lub widoku kontrolera można wywołać konsolę, wywołując metodę console .
Na przykład w kontrolerze:
class PostsController < ApplicationController
def new
console
@post = Post.new
end
end
Lub w widoku:
<% console %>
<h2>New Post</h2>
Spowoduje renderowanie konsoli wewnątrz widoku. Nie musisz dbać o lokalizację wywołania konsoli; nie będzie ono renderowane na miejscu wywołania, ale obok zawartości HTML.
Zobacz: http://guides.rubyonrails.org/debugging_rails_applications.html
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-24 07:18:48
Jeśli dodałeś własny helper i chcesz, aby jego metody były dostępne w konsoli do:
- w konsoli wykonaj
include YourHelperName
- Twoje metody pomocnicze są teraz dostępne w konsoli, użyj ich wywołania
method_name(args)
w konsoli.
Przykład: powiedzmy, że masz MyHelper (z metodą my_method
) w 'app/helpers/my_helper.rb`, następnie w konsoli do:
include MyHelper
my_helper.my_method
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-08 07:15:27