كيف يمكنني استدعاء أساليب التحكم/العرض من وحدة التحكم في Rails؟

StackOverflow https://stackoverflow.com/questions/151030

  •  02-07-2019
  •  | 
  •  

سؤال

عندما أقوم بالتحميل script/console, في بعض الأحيان أرغب في اللعب باستخدام مخرجات وحدة التحكم أو طريقة العرض المساعدة.

هل هناك طرق ل:

  • محاكاة الطلب؟
  • طرق الاتصال من مثيل وحدة تحكم بناء على الطلب المذكور؟
  • اختبار الأساليب المساعدة، إما عبر مثيل وحدة التحكم المذكورة أو بطريقة أخرى؟
هل كانت مفيدة؟

المحلول

للاتصال بالمساعدين، استخدم helper هدف:

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

إذا كنت تريد استخدام مساعد لم يتم تضمينه افتراضيًا (على سبيل المثال، لأنك قمت بإزالة helper :all من ApplicationController)، فقط قم بتضمين المساعد.

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

وأما التعامل مع وحدات تحكم, ، انا اقتبس نيك إجابة:

> 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

كائن التطبيق هو مثيل لـ ActionController::Integration::Session

هذا يناسبني باستخدام Rails 2.1 و2.3، ولم أجرب الإصدارات السابقة.

إذا كنت بحاجة إلى الاختبار من وحدة التحكم (تم اختباره على Rails 3.1 و4.1):

إجراءات وحدة تحكم الاتصال:

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

طرق تحكم التطبيق:

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

مساعدو الطريق:

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

عرض المساعدين:

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

يجعل:

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'

طرق الدعم النشط:

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

وحدات ليب:

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

إليك طريقة واحدة للقيام بذلك من خلال وحدة التحكم:

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

إنشاء مثيل جديد ل ActionView::Base يتيح لك الوصول إلى طرق العرض العادية التي من المحتمل أن يستخدمها مساعدك.ثم تمتد YourHelperModule يمزج أساليبه في الكائن الخاص بك مما يتيح لك عرض قيم الإرجاع الخاصة بهم.

هناك طريقة أخرى للقيام بذلك وهي استخدام مصحح أخطاء Rails.يوجد دليل Rails حول تصحيح الأخطاء في http://guides.rubyonrails.org/debugging_rails_applications.html

بشكل أساسي، قم بتشغيل الخادم باستخدام الخيار -u:

./script/server -u

ثم قم بإدراج نقطة توقف في البرنامج النصي الخاص بك حيث ترغب في الوصول إلى وحدات التحكم/المساعدين/إلخ.

class EventsController < ApplicationController
  def index
    debugger
  end
end

وعندما تقدم طلبًا وتضغط على هذا الجزء من الكود، ستعيد وحدة تحكم الخادم مطالبة حيث يمكنك بعد ذلك تقديم الطلبات وعرض الكائنات وما إلى ذلك.من موجه الأوامر.عند الانتهاء، فقط اكتب "cont" لمواصلة التنفيذ.هناك أيضًا خيارات لتصحيح الأخطاء الممتد، ولكن هذا يجب أن يساعدك على البدء على الأقل.

إذا كانت الطريقة POST الطريقة إذن

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

[هنا ستكون المعلمات حسب إمكانية تطبيقك]

آخر إذا كان GET الطريقة إذن

app.get 'controller/action'

فيما يلي كيفية تقديم طلب POST مصادق عليه، باستخدام المصفاة كمثال:

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

قد تجد هذه مفيدة أيضًا إذا تلقيت خطأ:

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

يمكنك الوصول إلى الأساليب الخاصة بك في Rails Console مثل ما يلي

controller.method_name
helper.method_name

في Rails 3، جرب هذا:

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

سيحتوي النص على HTML لعنوان url.

كيفية التوجيه والعرض (الإرسال) من نموذج في Rails 3

الإجابات السابقة تستدعي المساعدين ولكن الإجابات التالية ستساعد في استدعاء أساليب التحكم.لقد استخدمت هذا على القضبان 2.3.2.

قم أولاً بإضافة الكود التالي إلى ملف .irbrc الخاص بك (والذي يمكن أن يكون في الدليل الرئيسي الخاص بك)

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

ثم في وحدة التحكم Rails، يمكنك كتابة شيء مثل...

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

... وسيتم تفريغ HTML إلى وحدة التحكم.

داخل أي إجراء أو عرض لوحدة التحكم، يمكنك استدعاء وحدة التحكم عن طريق استدعاء وحدة التحكم طريقة.

على سبيل المثال، في وحدة التحكم:

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

أو في عرض:

<% console %>

<h2>New Post</h2>

سيؤدي هذا إلى عرض وحدة تحكم داخل طريقة العرض الخاصة بك.لا تحتاج إلى الاهتمام بموقع مكالمة وحدة التحكم؛لن يتم عرضه في مكان استدعائه ولكن بجوار محتوى HTML الخاص بك.

يرى: http://guides.rubyonrails.org/debugging_rails_applications.html

أحد الأساليب الممكنة لاختبار أسلوب المساعد في وحدة تحكم Rails هو

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

ولإعادة التحميل والقيام به

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

بالنسبة لوحدات التحكم، يمكنك إنشاء كائن وحدة التحكم في وحدة تحكم Rails.

على سبيل المثال،

class CustomPagesController < ApplicationController

  def index
    @customs = CustomPage.all
  end

  def get_number
    puts "Got the Number"
  end

  protected

  def get_private_number
    puts 'Got private Number'
  end

end

custom = CustomPagesController.new
2.1.5 :011 > custom = CustomPagesController.new
 => #<CustomPagesController:0xb594f77c @_action_has_layout=true, @_routes=nil, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil> 
2.1.5 :014 > custom.get_number
Got the Number
 => nil

# For calling private or protected methods,
2.1.5 :048 > custom.send(:get_private_number)
Got private Number
 => nil

إذا قمت بإضافة المساعد الخاص بك وتريد أن تكون طرقه متاحة في وحدة التحكم، فقم بما يلي:

  1. في تنفيذ وحدة التحكم include YourHelperName
  2. أساليب المساعدة الخاصة بك متاحة الآن في وحدة التحكم، استخدمها للاتصال method_name(args) في وحدة التحكم.

مثال:لنفترض أن لديك MyHelper (بطريقة my_method) في "app/helpers/my_helper.rb"، ثم في وحدة التحكم قم بما يلي:

  1. include MyHelper
  2. my_helper.my_method
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top