Re: [DataMapper] Adding custom methods to a model ?

31 views
Skip to first unread message

Antonio Antillon

unread,
Mar 7, 2013, 5:05:52 PM3/7/13
to datam...@googlegroups.com
what you're doing there is defining a class method named more_than_fifty?
a method declared like that can be called from the class itself, not an instance of it.

So, you end up with:
Day.more_than_fifty?

instead of:
day = Day.new
day.more_tan_fifty?

to add instance methods to a class, just declare them like this:

def method_name
  # do something
end

that is, without using self


On Thu, Mar 7, 2013 at 9:55 AM, Pierre-Adrien Buisson <pabu...@gmail.com> wrote:
Hey guys,

I'm beginning with Sinatra and using DataMapper as my ORM tool of choice. I've been doing great, playing with this today, but I'm now stuck. I'd like to add a custom method to one of my models, that would check some values of an instance, make some comparisons and return a boolean.

I tried the following :

class Day
    include DataMapper::Resource

    property :id, Serial
    property :day_number, Integer
    property :status, Integer, :default => 0
    property :date, Date

    def self.more_than_fifty?
        # Just for the sake of the example
        rand(1..100) > 50
    end

end

But didn't work. I've seen one or two cryptic messages on Stack Overflow about DataMapper::Model.append_inclusions, but not enough for me to understand and get it working.
Anyone who could help me around here ? Thanks a lot for your time guys.

Paddy

--
You received this message because you are subscribed to the Google Groups "DataMapper" group.
To unsubscribe from this group and stop receiving emails from it, send an email to datamapper+...@googlegroups.com.
To post to this group, send email to datam...@googlegroups.com.
Visit this group at http://groups.google.com/group/datamapper?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Pierre-Adrien Buisson

unread,
Mar 11, 2013, 6:20:40 AM3/11/13
to datam...@googlegroups.com
Well, I'm pretty confused... Defining my method as an instance method didn't seem to work when I tried it. I checked it again this morning and... boum, it's working. Really doesn't have a clue why it didn't work at first and works today, I must have missed something last time.

Anyway thanks a lot for your answer, and sorry for this dumb question.
Cheers
Reply all
Reply to author
Forward
0 new messages