简体   繁体   English

如何在rails 4.2中扩展模型

[英]How to extend model in rails 4.2

I have a user model 我有一个用户模型

class User

 def fname
    @fname
 end

 def fname=(str)
    @fname = str
 end

 def greeting
    "Hello #{@fname}"
 end

end

But I want to remove the greeting method to somewhere else so that my user model don't include the business logic. 但是我想将greeting方法移到其他地方,以便我的用户模型不包含业务逻辑。 How should I achieved that? 我该怎么做到这一点? I try to create a module(foo.rb) in lib but its not working. 我尝试在lib中创建一个模块(foo.rb),但它不起作用。 Should I include in User model? 我应该包含在用户模型中吗?

Updated Info: I updated my code 更新的信息:我更新了我的代码

            module UserBusinessEntity
              def speak(sound)
                return "#{sound} is its sound"
              end

              def greeting
                "#{self.id} Hello, #{self.fname} #{self.lname} you are #{self.age} years old"
              end
            end


            class User < ActiveRecord::Base
                include UserBusinessEntity
            end

This works if both code in same file. 这两个代码都在同一个文件中。 ie app/models/User.rb But I want to move the module UserBusinessEntity code to app/services/ ie app/models/User.rb但我想将module UserBusinessEntity代码移动到app/services/

Do I have to add require at User Model. 我是否必须在用户模型中添加需求。 If so I added like require UserBusinessEntity But Its gives uninitialized constant UserBusinessEntity 如果是这样我添加了像require UserBusinessEntity但它给了uninitialized constant UserBusinessEntity

I believe you may use greeting to render in views or mailers. 我相信你可以使用greeting在视图或邮件中呈现。 So this is a showcase of using presenter. 所以这是使用演示者的展示。 A good article is here. 这里有一篇文章

Basically, defining a presenter will be: 基本上,定义演示者将是:

app/presenters/user_presenter.rb 应用程序/主持人/ user_presenter.rb

class UserPresenter < DelegateClass(User)
  def greeting
    "Hello #{fname}"
  end
end

There are many ways to define, the above is just basic, check out above article for detail. 有很多方法可以定义,上面只是基本的,详见上面的文章。

Then, you can use it anywhere you want to: 然后,您可以在任何地方使用它:

@user = User.first
UserPresenter.new(user).greeting

Or even in a view 甚至在一个视图中

example.html.erb example.html.erb

<p><%= UserPresenter.new(user).greeting %><p>

Moreover, people may use concern to implement this, but with me that is not a good practice! 而且,人们可能会用关注来实现这一点,但对我来说这不是一个好习惯!

Just create a module like this: 只需创建一个这样的模块:

module Foo
  def greeting
    "Hello #{self.fname}"
  end
end

Then include the module in your User module: 然后在您的用户模块中包含该模块:

class User
  include Foo
  # ...
end

Then you can call in a controller or a view 然后你可以调用控制器或视图

@user = User.new
@user.greeting

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM