How to get DataMapper resource serial and key attributes in Ruby? - ruby

I`m trying to figure out how to get serial and key attributes set for Resource object. Basic method DataMapper::Resource.attributes returns a collection of properties, but it does not say anything about types. Of course i can check it via system call: obj.class, but cant understand how to get type information from resource instance.
Example:
class Foo
include DataMapper::Resource
property :id, Serial
property :title, String, :required => true
property :created_at, Time, :required => true
property :flagged, Boolean, :default => false
end
So, is there any way to get this information about internal types for resource?

Not long time ago, i figured it out by myself. All model fields are basically instances of DataMapper::Property
So, all you need is to call ModelName.properties and get options like :index, :key, etc.
Description: http://yardoc.org/docs/datamapper-dm-core/DataMapper/Property

Related

Ruby: What is it declare in a class?

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
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.

How does DataMapper gem separate the application logic and data persistence?

This is a get started example of Ruby data mapper. However, how does this example illustrate the power of datamapper that separate the application logic and data persistence?
Any better example can give us that the separation can lead us do unit test more easily?
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
# create makes the resource immediately
#post = Post.create(
:title => "My first DataMapper post",
:body => "A lot of text ...",
:created_at => Time.now
)
# Or new gives you it back unsaved, for more operations
#post = Post.new(:title => ..., ...)
#post.save # persist the resource
Thanks!

Create JSON from 2 associated Datamapper models

Here is my question.
I have 2 associated Datamapper models:
class Task
include DataMapper::Resource
property :id, Serial
property :date, Date
property :amount, Float
belongs_to :project, :required => true
end
class Project
include DataMapper::Resource
property :id, Serial
property :name, String, :required => true
property :desc, Text
belongs_to :company
has n, :tasks
end
My goal is to created JSON that will contain task date, amount and project name, that should be matched by project_id. At the moment JSON generation has following look:
Task.all.to_json(:only => [:date, :amount, :project_id])
I can access project_id from Task model, but have no idea how to add respective project name from Project model for every task. In SQL it looks like join:
select tasks.date, tasks.amount, projects.name from tasks
inner join projects
on tasks.project_id = projects.id;
Can you suggest correct way to create final JSON, using Datamapper way, but not SQL?
Thank you.
I have found solution for my problem. Here it is:
# create new structure to store merged result
Task_entry = Struct.new(:date, :amount, :pname)
# array to get results from database
all_task_items = Array.new
# run through result and fill the array with required data
Task.all.each do |task|
task_item = Task_entry.new(task.date, task.amount, task.project.name)
all_task_items << task_item
end
all_task_items.to_json # generate json
It works for me well. Hope it can be helpful.

Is 'valid' a reserved name in DataMapper?

I have the following model in datamapper:
class Student
include DataMapper::Resource
property :id, Serial
# <snip>
property :permissions, String, :accessor => :protected, :required => true, :default => 'standard'
property :valid, Boolean, :default => false, :required => true
# <snip>
end
After requiring 'dm-validations' (version 1.1.0), and starting my Sinatra app, I recieve the following message:
/Library/Ruby/Gems/1.8/gems/dm-validations-1.1.0/lib/dm-validations.rb:81:in `valid?': wrong number of arguments (1 for 0) (ArgumentError)
from /Library/Ruby/Gems/1.8/gems/dm-validations-1.1.0/lib/dm-validations.rb:81:in `save_self'
from /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/resource.rb:1007:in `_save'
from /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/resource.rb:1223:in `run_once'
from /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/resource.rb:1006:in `_save'
from /Library/Ruby/Gems/1.8/gems/dm-core-1.1.0/lib/dm-core/resource.rb:406:in `save'
from /Library/Ruby/Gems/1.8/gems/dm-validations-1.1.0/lib/dm-validations.rb:69:in `save'
from /Library/Ruby/Gems/1.8/gems/dm-validations-1.1.0/lib/dm-validations/support/context.rb:30:in `validation_context'
from /Library/Ruby/Gems/1.8/gems/dm-validations-1.1.0/lib/dm-validations.rb:69:in `save'
<snip>
Is the 'valid' name I'm using for my model a reserved word? If it is, where can I find these words. I'm to the point of going on to trying to name it something like: 'student_valid' but now i'm just really curious about this.
Thanks
#valid? is a method that dm-validations adds. You cannot use "valid" as a property name because it automatically defines "valid?" method for a boolean property type which overrides dm-validations' valid?. Hence the error.
That's a tricky situation, I guess we need to improve the way we validate property names. Thanks for reporting this.
Well the way datamapper works, is that it uses method_missing at the end of the method call chain and finds your property. If there is a method with this same name then that is called rather than your property. Datamapper mixes in Validatable which has the method valid? Most of the time you learn what is reserved (Like all Object methods etc.) But if you want a full list you can do:
`myinstance.methods`
Anything that appears there will get called first.

DataMapper has n with conditions

By any chance is it possible to create a conditional association with DataMapper?
For example:
I want the User have n Apps just if that user have the attribute :developer => true
something like this:
class User
include DataMapper::Resource
property :id, Serial
property :name, String, :nullable => false
property :screen_name, String, :nullable => false, :unique => true
property :email, String, :nullable => false, :unique => true, :format => :email_address
property :password, BCryptHash, :nullable => false
property :developer, Boolean, :default => false
#The user just gets apps if developer
has n :apps #,:conditions => "developer = 't'"
end
class App
include DataMapper::Resource
property :id, Serial
property :name, String, :nullable => false
belongs_to :user
end
I know that this would be possible by creating a subclass from User as a Developer::User and in that class, use the has n, but I really would like to know if its possible to make it directly on the association declaration.
Another way I also managed to do when using ARn was to extend the association and rewriting the methods for each action.
So on the extension module I could have something like this:
module PreventDeveloperActions
def new
if proxy_owner.developer?
super
else
raise NoMethodError, "Only Developers can create new applications"
end
end
# and so on for all the actions ...
end
But again, I really would like to avoid the use of this solutions if possible, but just if it's possible to perform a quick and direct method easily with DataMapper :)
Thanks in advance
At the moment, conditions that you include in the relationship declaration only apply to the target. So if the target model has an :active property, you can say things like has n, :apps, :active => true. Unfortunately you can't define relationships that are only active given the current state of the source (yet).
There are some proposals I'm considering to expand the Query logic in DM, but I'm unsure what the impact will be to the code, and what extra capabilities it will provide aside from this. It may be something we tackle after DM 1.0, since it also affects 50+ adapters and plugins.
STI is normally what I'd recommend for something like this, since it will allow you to define relationships that only exist for that type of object. Another approach would be to define the relationships as normal, mark the accessor/mutator methods as private, and then add a proxy method that does the equivalent of return apps if developer?.

Resources