简体   繁体   中英

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. How should I achieved that? I try to create a module(foo.rb) in lib but its not working. 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/

Do I have to add require at User Model. If so I added like require UserBusinessEntity But Its gives uninitialized constant UserBusinessEntity

I believe you may use greeting to render in views or mailers. So this is a showcase of using presenter. A good article is here.

Basically, defining a presenter will be:

app/presenters/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

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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