众所周知,在Ruby中,类方法得到了继承:
class P
def self.mm; puts 'abc' end
end
class Q < P; end
Q.mm # works
Run Code Online (Sandbox Code Playgroud)
然而,令我惊讶的是它不适用于mixins:
module M
def self.mm; puts 'mixin' end
end
class N; include M end
M.mm # works
N.mm # does not work!
Run Code Online (Sandbox Code Playgroud)
我知道#extend方法可以做到这一点:
module X; def mm; puts 'extender' end end
Y = Class.new.extend X
X.mm # works
Run Code Online (Sandbox Code Playgroud)
但我正在编写一个包含实例方法和类方法的mixin(或者,更愿意写):
module Common
def self.class_method; puts "class method here" end
def instance_method; puts "instance method here" end
end
Run Code Online (Sandbox Code Playgroud)
现在我想做的是:
class A; include Common
# custom …Run Code Online (Sandbox Code Playgroud) 我的UserMailer类有以下RSpec测试:
require "spec_helper"
describe UserMailer do
it "should send welcome emails" do
ActionMailer::Base.deliveries.should be_empty
user = Factory(:user)
UserMailer.welcome_email(user).deliver
ActionMailer::Base.deliveries.should_not be_empty
end
end
Run Code Online (Sandbox Code Playgroud)
这个测试第一次通过,但第二次运行失败了.在进行一些调试后,看起来第一个测试向ActionMailer :: Base.deliveries数组添加了一个项目,该项目从未被清除.这会导致测试中的第一行失败,因为数组不为空.
在RSpec测试之后清除ActionMailer :: Base.deliveries数组的最佳方法是什么?
我读过这篇文章:Ruby模块 - 包括do end block - 但是当你self.included do ... end在模块中使用块时仍然无法获得.
帖子说当你包含模块时,块中的代码将被运行,但是如果要包含模块的唯一目的,那么它的重点是什么?这个代码不需要运行吗?该块不需要存在就可以运行该代码,对吧?
下面两者之间有什么区别:
module M
def self.included(base)
base.extend ClassMethods
base.class_eval do
scope :disabled, -> { where(disabled: true) }
end
end
module ClassMethods
...
end
end
Run Code Online (Sandbox Code Playgroud)
与
module M
def self.some_class_method
...
end
scope :disabled, -> { where(disabled: true) }
end
Run Code Online (Sandbox Code Playgroud) 我正在尝试在我的开发环境中设置一个简单的contact_us页面,用户可以使用我创建的表单发送查询.我有ActiveMailer和Contact模型/控制器/视图都设置但它似乎没有正常工作.有任何想法吗?我的日志似乎显示正在发送的邮件.
的ActionMailer
class ContactConfirmation < ActionMailer::Base
default from: "from@example.com"
def receipt(contact)
@contact = contact
mail to: 'myname@example.com',
subject: contact.subject
end
end
Run Code Online (Sandbox Code Playgroud)
收据
<%= @contact.first_name %> <%= @contact.last_name %>
Writes:
<%= @contact.description %>
Run Code Online (Sandbox Code Playgroud)
ContactsController
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params)
if @contact.submit_contact_info
redirect_to users_path, notice: 'Submission successful. Somebody will get back to you shortly.'
else
render :new
end
end
protected
def contact_params
params.require(:contact).permit(:first_name, :last_name, :email, :subject, :description)
end
end
Run Code Online (Sandbox Code Playgroud)
联系型号
class Contact …Run Code Online (Sandbox Code Playgroud)