如何从 Ruby on Rails 的控制台调用控制器/视图帮助器方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/151030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:41:56  来源:igfitidea点击:

How can I call controller/view helper methods from the console in Ruby on Rails?

ruby-on-railsconsole

提问by kch

When I load script/console, sometimes I want to play with the output of a controller or a view helper method.

当我加载时script/console,有时我想使用控制器或视图助手方法的输出。

Are there ways to:

有没有办法:

  • simulate a request?
  • call methods from a controller instance on said request?
  • test helper methods, either via said controller instance or another way?
  • 模拟一个请求?
  • 根据所述请求从控制器实例调用方法?
  • 通过所述控制器实例或其他方式测试辅助方法?

回答by kch

To call helpers, use the helperobject:

要调用助手,请使用helper对象:

$ ./script/console
>> helper.number_to_currency('123.45')
=> "R$ 123,45"

If you want to use a helper that's not included by default (say, because you removed helper :allfrom ApplicationController), just include the helper.

如果您想使用默认情况下未包含的帮助程序(例如,因为您helper :all从 中删除ApplicationController),只需包含帮助程序。

>> include BogusHelper
>> helper.bogus
=> "bogus output"

As for dealing with controllers, I quote Nick'sanswer:

至于处理控制器,我引用尼克的回答:

> 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
> 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

回答by Nick

An easy way to call a controller action from a script/console and view/manipulate the response object is:

从脚本/控制台调用控制器操作并查看/操作响应对象的一种简单方法是:

> app.get '/posts/1'
> response = app.response
# You now have a Ruby on Rails response object much like the integration tests

> response.body            # Get you the HTML
> response.cookies         # Hash of the cookies

# etc., etc.

The app object is an instance of ActionController::Integration::Session

app 对象是ActionController::Integration::Session 的一个实例

This works for me using Ruby on Rails 2.1 and 2.3, and I did not try earlier versions.

这对我使用 Ruby on Rails 2.1 和 2.3 有效,我没有尝试早期版本。

回答by Fernando Fabreti

If you need to test from the console (tested on Ruby on Rails 3.1 and 4.1):

如果您需要从控制台进行测试(在 Ruby on Rails 3.1 和 4.1 上测试):

Call Controller Actions:

调用控制器操作:

app.get '/'
   app.response
   app.response.headers  # => { "Content-Type"=>"text/html", ... }
   app.response.body     # => "<!DOCTYPE html>\n<html>\n\n<head>\n..."

ApplicationController methods:

应用控制器方法:

foo = ActionController::Base::ApplicationController.new
foo.public_methods(true||false).sort
foo.some_method

Route Helpers:

路线助手:

app.myresource_path     # => "/myresource"
app.myresource_url      # => "http://www.example.com/myresource"

View Helpers:

查看助手:

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'

ActiveSupport methods:

ActiveSupport 方法:

require 'active_support/all'
1.week.ago
=> 2013-08-31 10:07:26 -0300
a = {'a'=>123}
a.symbolize_keys
=> {:a=>123}

Lib modules:

库模块:

> require 'my_utils'
 => true
> include MyUtils
 => Object
> MyUtils.say "hi"
evaluate: hi
 => true

回答by Gordon Wilson

Here's one way to do this through the console:

这是通过控制台执行此操作的一种方法:

>> 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>"

Creating a new instance of ActionView::Basegives you access to the normal view methods that your helper likely uses. Then extending YourHelperModulemixes its methods into your object letting you view their return values.

创建一个新实例ActionView::Base使您可以访问您的助手可能使用的普通视图方法。然后扩展YourHelperModule将其方法混合到您的对象中,让您查看它们的返回值。

回答by Swapnil Chincholkar

If the method is the POSTmethod then:

如果方法是POST方法,则:

app.post 'controller/action?parameter1=value1&parameter2=value2'

(Here parameters will be as per your applicability.)

(这里的参数将根据您的适用性而定。)

Else if it is the GETmethod then:

否则,如果是GET方法,则:

app.get 'controller/action'

回答by Dan McNevin

Another way to do this is to use the Ruby on Rails debugger. There's a Ruby on Rails guide about debugging at http://guides.rubyonrails.org/debugging_rails_applications.html

另一种方法是使用 Ruby on Rails 调试器。在http://guides.rubyonrails.org/debugging_rails_applications.html上有一个关于调试的 Ruby on Rails 指南

Basically, start the server with the -u option:

基本上,使用 -u 选项启动服务器:

./script/server -u

And then insert a breakpoint into your script where you would like to have access to the controllers, helpers, etc.

然后在您的脚本中插入一个断点,您可以在其中访问控制器、助手等。

class EventsController < ApplicationController
  def index
    debugger
  end
end

And when you make a request and hit that part in the code, the server console will return a prompt where you can then make requests, view objects, etc. from a command prompt. When finished, just type 'cont' to continue execution. There are also options for extended debugging, but this should at least get you started.

当您发出请求并点击代码中的该部分时,服务器控制台将返回一个提示,您可以在其中从命令提示符发出请求、查看对象等。完成后,只需键入“cont”即可继续执行。还有用于扩展调试的选项,但这至少应该让您开始。

回答by Chloe

Here is how to make an authenticated POST request, using Refinery as an example:

以下是如何发出经过身份验证的 POST 请求,以 Refinery 为例:

# 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}

You might find these useful too if you get an error:

如果出现错误,您可能会发现这些也很有用:

app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML

回答by Jyothu

You can access your methods in the Ruby on Rails console like the following:

您可以在 Ruby on Rails 控制台中访问您的方法,如下所示:

controller.method_name
helper.method_name

回答by Tbabs

In Ruby on Rails 3, try this:

在 Ruby on Rails 3 中,试试这个:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body

The body will contain the HTML of the URL.

正文将包含 URL 的 HTML。

How to route and render (dispatch) from a model in Ruby on Rails 3

如何从 Ruby on Rails 3 中的模型路由和渲染(调度)

回答by David Knight

The earlier answers are calling helpers, but the following will help for calling controller methods. I have used this on Ruby on Rails 2.3.2.

较早的答案是调用助手,但以下将有助于调用控制器方法。我在 Ruby on Rails 2.3.2 上使用过它。

First add the following code to your .irbrc file (which can be in your home directory)

首先将以下代码添加到您的 .irbrc 文件(可以在您的主目录中)

class Object
   def request(options = {})
     url=app.url_for(options)
     app.get(url)
     puts app.html_document.root.to_s
  end
end

Then in the Ruby on Rails console you can type something like...

然后在 Ruby on Rails 控制台中,您可以键入类似...

request(:controller => :show, :action => :show_frontpage)

...and the HTML will be dumped to the console.

...并且 HTML 将被转储到控制台。