Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Casting of boolean values #59

Open
dmarkow opened this issue Oct 2, 2014 · 4 comments
Open

Casting of boolean values #59

dmarkow opened this issue Oct 2, 2014 · 4 comments

Comments

@dmarkow
Copy link

dmarkow commented Oct 2, 2014

Boolean values are stored as 0/1, and that's what CDQ returns when you query an object. Since ruby treats 0 as a truthy value, you can't do something like if person.happy, but instead have to do if person.happy == 1. I'm new to CDQ, so I'm not sure if this is something that should be cast to true/false automatically?

Sample schema:

schema "0001 initial" do
  entity "Person" do
    boolean :happy
  end
end

Sample REPL code:

(main)> p = Person.create(happy: false)
=> <Person: 0xb622490> (entity: Person; id: 0xb621a60 <x-coredata:///Person/tE660D344-00B6-4A86-A0BE-84A6EE30E7324> ; data: {
    happy = 0;
})
(main)> p.happy
=> 0
(main)> p.happy = true
=> true
(main)> p.happy
=> 1
@kemiller
Copy link
Contributor

kemiller commented Oct 2, 2014

It's not trivial to do that because of the way core data works. You can't do it right in CDQManagedObject because CoreData will subclass your class and then add the property accessors rather than the other way around as in ActiveRecord. To work around that you can define question-mark predicate methods ("happy?"). To do it automatically you have to dig into Objective C, so I haven't got around to it.

@pixlwave
Copy link
Contributor

Couldn't this be done with ruby's define_method? As long as you have a list of boolean properties (which we have in the schema), you could run something like this:

def self.define_predicate_methods

  bool_methods.each do |method|
    define_method("#{method}?") do
      self.send(method).boolValue
    end
  end

end

@pixlwave
Copy link
Contributor

Just updating the snippet slightly, after realising that it didn't handle nil being returned. A better implementation would be:

def self.define_predicate_methods

  methods.each do |method|
    define_method("#{method}?") do
      value = self.send(method)
      value.nil? ? value : value.boolValue
    end
  end

end

@kemiller
Copy link
Contributor

kemiller commented Apr 4, 2015

I'm don't remember why define_method didn't work for me, but if you can make it work, great. MotionData used Objective-C to get this feature, for what it's worth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants