Skip to content

Instantly share code, notes, and snippets.

@toamitkumar
Forked from naoyamakino/REPL
Created November 10, 2012 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toamitkumar/4050094 to your computer and use it in GitHub Desktop.
Save toamitkumar/4050094 to your computer and use it in GitHub Desktop.
using NanoStore::Model to do basic relations.
class Car < NanoStore::Model
attribute :name
attribute :year
attribute :user_id
def user
User.find(:id => user_id).first
end
def self.create(name, year, user_id)
car = Car.new
car.name = name
car.year = year
car.user_id = user_id
car
end
end
class User < NanoStore::Model
attribute :id
attribute :name
attribute :age
attribute :created_at
attribute :cars_bag_name
def self.create(id, name, age, cars_bag_name)
user = User.new
user.name = name
user.age = age
user.id = id
user.created_at = Time.now
user.cars_bag_name = cars_bag_name
user
end
def cars
cars = []
bag = NanoStore.shared_store.bagWithName(cars_bag_name)
if bag
bag.savedObjects.merge(bag.unsavedObjects).each do |k, v|
cars << v
end
end
cars
end
end
(main)> bag = NanoStore::Bag.bag
=> #<NanoStore::Bag:0x8c930b0>
(main)> NanoStore.shared_store.addObject(bag, error:nil)
=> true
(main)> bag.setName "cars"
=> #<NanoStore::Bag:0x8c930b0>
(main)> user = User.create(8, 'demo', 23, bag.name)
=> #<User:0x8c93800>
(main)> user.save
=> #<User:0x8c93800>
(main)> car = Car.create('toyota', 1986, user.id)
=> #<Car:0x8db1c00>
(main)> bag << car
=> #<NanoStore::Bag:0x8c930b0>
(main)> car = Car.create('toyota 2', 1988, user.id)
=> #<Car:0x8db2030>
(main)> bag << car
=> #<NanoStore::Bag:0x8c930b0>
(main)> bag.save
=> true
(main)> user.cars
=> [#<Car:0x8c7d040>, #<Car:0x8c7a3f0>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment