Reputation: 15257
I am using Ruby on Rails 4 and I would like to provide more functionality for attribute methods. That is:
Given I have the following model class
class Article < ActiveRecord::Base
...
end
And given Article
instances have the following attribute methods
@article.title # => "Sample title"
@article.content # => "Sample content"
Then I would like to add to Article
functionality as like the following:
class Article < ActiveRecord::Base
def title(args)
# Some logic...
self.title
end
def content(args)
# Some logic...
self.content
end
end
@article.title(args)
@article.content(args)
Is the above approach safe / correct / valid? Will I have issues?
Upvotes: 0
Views: 38
Reputation: 8295
I would suggest that you read 7 Patterns to Refactor Fat ActiveRecord Models. What you want can be a nice decorator or value object.
class Title
def initialize(article)
@article = article
end
def weird_title
some_logic
end
end
and when the weird_title
is needed on an article article_1
Title(article_1).weird_title
Thus you have a good code separation (OOP style) and you keep your model clean.
Upvotes: 0
Reputation: 16002
You're overriding title
and content
methods, and as far as I know this approach isn't safe at all. Like, having getter and setter methods is a completely different story. But, this pattern will confuse you and other developers after some time.
And if I'm right(correct me if I'm wrong, please), you must get
wrong number of arguments (0 for 1)
error for title
and content
at line number where you have:
self.title
and self.content
when you do:
@article.title(args)
@article.content(args)
Upvotes: 1