先看下面 ?? 兩個(gè) model
# app/models/accout.rb
class Account < ActiveRecord::Base
def message(content)
"Message: #{content}"
end
end
# app/models/user.rb
class User < ActiveRecord::Base
def message(content)
"Message: #{content}"
end
end
兩個(gè)類存在同樣的方法,這種情況下我們可以使用叙赚,ActiveSupport::Concern
來將這一段代碼提出來礁叔,簡化我們的類。
# app/modles/concerns/common.rb
module Common extend ActiveSupport::Concern # 這里的繼承一定不要忘記了
# 可以將重復(fù)的代碼都提取到這里
def message(content)
"Message: #{content}"
end
end
重構(gòu)原本的兩個(gè)類插勤,將 Common
包含進(jìn)去。
# app/models/accout.rb
class Account < ActiveRecord::Base
include Common
end
# app/models/user.rb
class User < ActiveRecord::Base
include Common
end
測試一下我們的代碼
$ rails c
Running via Spring preloader in process 11485
Loading development environment (Rails 4.2.0)
irb(main):001:0> Account.new.message "hello world!"
=> "hello world!"
irb(main):001:0> User.new.message "hello world!"
=> "hello world!"