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 => 'Bar').find_nouns
The problem is, the base class doesn’t have access to the find_nouns method — it belongs to StoryParser.
Your
Parserclass looks like it should be a module mixed into either theStoryclass or instances, because it’s one aspect of a story.http://en.wikipedia.org/wiki/Aspect-oriented_programming
Here’s the module:
Mix it into the class with
include:Or mix it into instances of
Story: