0

I got this sample code from datamapper http://datamapper.org/getting-started.html

class Post
  include DataMapper::Resource

  property :id,         Serial    # An auto-increment integer key
  property :title,      String    # A varchar type string, for short strings
  property :body,       Text      # A text block, for longer string data.
  property :created_at, DateTime  # A DateTime, for any date you might like.
end

Can anyone tell me that how "property" generate? Is it a function, variable, class variable or instance variable or a constant?

sometime i also saw this kind of code

class CarModel
   attribute :name
   attribute :hello
end

but no idea how does this generate

4
  • I think you may be meaning something other than "how xxx generate". property is a method, as is attribute. Both are being called/invoked within the class definition. What they "do" is a separate question. Commented Dec 4, 2013 at 1:45
  • so are they a method bening invoked every thing when class is initialized? Commented Dec 4, 2013 at 1:50
  • is there any name of how this pattern they called? Commented Dec 4, 2013 at 1:50
  • property :id, Serial is just call of function with 2 arguments. It changes class (adds property). It's meta-programming tip. Ruby has a lot of it. Commented Dec 4, 2013 at 1:51

1 Answer 1

1

It is a method that is included when you do:

include DataMapper::Resource

You can see its source code here if you're interested in digging in deeper.

It basically adds a property to the list of properties in your Post resource.

Sign up to request clarification or add additional context in comments.

4 Comments

so property function will be executed when we initialize the class?
Yes, it is called when the class is initialised (when its source code is loaded). Also Ruby does not have functions, it is a method.
@KitHo Don't confuse "when class is initialized" with "when an instance of the class is created". property and attribute are only called once per their occurrence in the code - when the class itself is defined/initialized.
Is there any name for this kind of pattern , so that i can search more on google. I never find this pattern in java/c++ code before

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.