¿Cómo puedo llamar a los métodos controller/view desde la consola en Rails?


Cuando cargo script/console, algunas veces quiero jugar con la salida de un controlador o un método auxiliar de vista.

Hay maneras de:

  • simular una solicitud?
  • métodos de llamada desde una instancia de controlador en dicha solicitud?
  • ¿probar métodos auxiliares, ya sea a través de dicha instancia de controlador o de otra manera?
Author: kch, 2008-09-30

13 answers

Para llamar a los ayudantes, utilice el objeto helper:

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

Si desea utilizar un helper que no está incluido por defecto (por ejemplo, porque eliminó helper :all de ApplicationController), simplemente incluya el helper.

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

En cuanto a tratar con controladores , cito La respuesta de Nick :

> 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
 454
Author: kch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:37

Una forma fácil de llamar a una acción del controlador desde script/consola y ver/manipular el objeto de respuesta es:

> 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

El objeto app es una instancia de ActionController::Integration:: Session

Esto funciona para mí usando Rails 2.1 y 2.3, no probé versiones anteriores.

 136
Author: Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 20:57:41

Si necesita probar desde la consola (probado en Rails 3.1 y 4.1):

Llamar al controlador Acciones:

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

Métodos del controlador de aplicación:

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

Ayudantes de ruta:

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

Ver ayudantes:

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'

Métodos de soporte activo:

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

Módulos Lib:

> require 'my_utils'
 => true 
> include MyUtils
 => Object 
> MyUtils.say "hi"
evaluate: hi
 => true 
 94
Author: Fernando Fabreti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-29 13:31:28

Aquí hay una manera de hacer esto a través de la consola:

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

Crear una nueva instancia de ActionView::Base le da acceso a los métodos de vista normales que su ayudante probablemente usa. Luego, extending YourHelperModule mezcla sus métodos en su objeto, lo que le permite ver sus valores de retorno.

 72
Author: Gordon Wilson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-30 00:19:53

Otra forma de hacer esto es usar el depurador rails. Hay una guía de Rails sobre la depuración en http://guides.rubyonrails.org/debugging_rails_applications.html

Básicamente, inicie el servidor con la opción-u:

./script/server -u

Y luego inserte un punto de interrupción en su script donde le gustaría tener acceso a los controladores/helpers/etc..

class EventsController < ApplicationController
  def index
    debugger
  end
end

Y cuando realice una solicitud y presione esa parte en el código, la consola del servidor devolverá un mensaje donde puede luego haga solicitudes, vea objetos, etc.. desde un símbolo del sistema. Cuando haya terminado, simplemente escriba 'cont' para continuar la ejecución. También hay opciones para la depuración extendida, pero esto debería al menos ayudarte a comenzar.

 15
Author: Dan McNevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-27 03:30:23

Si el método es POST método entonces

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

[aquí los parámetros serán según su aplicabilidad]

Si no es GET método entonces

app.get 'controller/action'
 14
Author: Swapnil Chincholkar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-29 16:22:06

Puede acceder a sus métodos en la consola de Rails como sigue

controller.method_name
helper.method_name
 10
Author: Jyothu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-30 11:22:39

Aquí está cómo hacer una solicitud POST autenticada, usando Refinery como ejemplo:

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

Usted podría encontrar estos útiles también si obtiene un error:

app.cookies.to_hash
app.flash.to_hash
app.response # long, raw, HTML
 10
Author: Chloe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-28 21:40:15

En rails 3, prueba esto:

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

Body contendrá el HTML de la url.

Cómo enrutar y renderizar (despachar) desde un modelo en Rails 3

 8
Author: Tbabs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:50

Las respuestas anteriores están llamando a los ayudantes, pero lo siguiente ayudará a llamar a los métodos del controlador. He utilizado esto en rails 2.3.2.

Primero agregue el siguiente código a su .archivo irbrc (que puede estar en su directorio personal)

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

Luego en la consola de rails puede escribir algo así...

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

...y el html será volcado a la consola.

 7
Author: David Knight,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-07-25 23:58:25

Un enfoque posible para la prueba de métodos auxiliares en la consola de rails es

Struct.new(:t).extend(YourHelper).your_method(*arg)

Y para recargar y hacer

reload!; Struct.new(:t).extend(YourHelper).your_method(*arg)

 2
Author: dux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-15 08:57:31

Dentro de cualquier acción o vista del controlador, puede invocar la consola llamando al método console.

Por ejemplo, en un controlador:

class PostsController < ApplicationController
  def new
    console
    @post = Post.new
  end
end

O en una vista:

<% console %>

<h2>New Post</h2>

Esto renderizará una consola dentro de su vista. No necesita preocuparse por la ubicación de la llamada a la consola; no se renderizará en el lugar de su invocación, sino al lado de su contenido HTML.

Véase: http://guides.rubyonrails.org/debugging_rails_applications.html

 1
Author: Gayan Weerakutti,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-24 07:18:48

Si ha agregado su propio helper y desea que sus métodos estén disponibles en la consola, haga lo siguiente:

  1. en la consola ejecutar include YourHelperName
  2. sus métodos de ayuda ahora están disponibles en la consola, úselos llamando a method_name(args) en la consola.

Ejemplo: digamos que tienes MyHelper (con un método my_method) en 'app/helpers/my_helper.rb`, luego en la consola hacer:

  1. include MyHelper
  2. my_helper.my_method
 0
Author: Willmore,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-08 07:15:27