开发者

How to extend the functionality of an ActiveRecord object in Rails?

开发者 https://www.devze.com 2023-03-23 12:22 出处:网络
I have a class called Story that is associated with a class called User. I also have a class called Parser that extends Story with parsing abilities (such as finding the nouns, for example).

I have a class called Story that is associated with a class called User. I also have a class called Parser that extends Story with parsing abilities (such as finding the nouns, for example).

class User < ActiveRecord::Base
    has_many :stories
end

class Story < ActiveRecord::Base
    belongs_to :user
    attr_accessible :title, :content
end

class Parser < Story
    def find_nouns
        self.content.do_something
    end
end

Say I want to create a new story for the first user in my database. Normally, I would simply do that using

User.first.stories.new(:title => 'Foo', :content => 'Bar')

How would I achieve that and still associate the record with the first story elegantly?

Something along these line:

User.first.stories.new(:title => 'Foo', :content => 开发者_StackOverflow中文版'Bar').find_nouns

The problem is, the base class doesn't have access to the find_nouns method -- it belongs to StoryParser.


Your Parser class looks like it should be a module mixed into either the Story class or instances, because it's one aspect of a story.

http://en.wikipedia.org/wiki/Aspect-oriented_programming

Here's the module:

module Parser
  def find_nouns
    ...
  end
end

Mix it into the class with include:

class Story
  include Parser
end

Or mix it into instances of Story:

@user.stories.first.extend(Parser).find_nouns


Does not look like Parser is related to Story, parser should be it's own class and should have methods that receive a Story or just pure strings and parse them to do their work.

Stories do not "extract" nouns from themselves, so it does not really make sense to Parser be a subclass of Story.

story = Story.new(:content => 'some content')
parser = Parser.new
parser.find_nouns( story.content ) # would generate ['content']
0

精彩评论

暂无评论...
验证码 换一张
取 消