ActiveSupport::Concern 的使用

先看下面 👇 两个 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

两个类存在同样的方法,这种情况下我们可以使用,ActiveSupport::Concern 来将这一段代码提出来,简化我们的类。

# app/modles/concerns/common.rb
module Common extend ActiveSupport::Concern # 这里的继承一定不要忘记了
  # 可以将重复的代码都提取到这里
  def message(content)
    "Message: #{content}"
  end
end

重构原本的两个类,将 Common 包含进去。

# 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!"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容