bsns 0.2.2 → 0.3.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (3) hide show
  1. data/lib/bsns.rb +14 -7
  2. data/spec/bsns_spec.rb +15 -0
  3. metadata +1 -1
data/lib/bsns.rb CHANGED
@@ -7,11 +7,12 @@ module BSNS
7
7
  def has_many model, opts = {}
8
8
  field = opts[:as] || model.to_s.downcase.pluralize
9
9
  with = opts[:with] || nil
10
+ embed = opts[:embedded] || false
10
11
  model = model.to_s.singularize
11
12
  class_eval do
12
13
  define_method field do
13
14
  fields = instance_variable_get "@#{field}"
14
- collection_from_array fields, model, with
15
+ collection_from_array fields, model, opts
15
16
  end
16
17
  end
17
18
  end
@@ -122,17 +123,23 @@ module BSNS
122
123
  get_v(:data)[f.to_s]
123
124
  end
124
125
 
125
- def collection_from_array arr, model, extra_key = nil
126
- # Return an array of all the references for a thing.
127
- arr.map do |d|
128
- if d.instance_of? Hash
126
+ # Return an array of all the references for a thing.
127
+ def collection_from_array arr, model, opts
128
+ extra_key = opts[:with]
129
+ arr.map do |d|
130
+ if d.instance_of?(Hash) && !opts[:embedded]
129
131
  # Normalize {:id => :linking_value} to [:id, :linking_value]
130
132
  id = d.keys[0]
131
133
  value = d[id]
132
134
  d = [id, value]
133
135
  end
134
- id = d.instance_of?(Array) ? d[0] : d
135
- obj = model.to_s.capitalize.constantize.load id
136
+ klass = obj = model.to_s.capitalize.constantize
137
+ if opts[:embedded]
138
+ obj = klass.new d
139
+ else
140
+ id = d.instance_of?(Array) ? d[0] : d
141
+ obj = klass.load id
142
+ end
136
143
  obj.define_linking_field extra_key, d[1] if extra_key
137
144
  obj
138
145
  end
data/spec/bsns_spec.rb CHANGED
@@ -29,6 +29,14 @@ class Fizzle < BSNS::Base
29
29
 
30
30
  has_many :fizzles
31
31
 
32
+ has_many :cats, :embedded => true
33
+
34
+ end
35
+
36
+ class Cat < BSNS::Base
37
+
38
+ attr_accessor :thing
39
+
32
40
  end
33
41
 
34
42
  describe BSNS do
@@ -111,4 +119,11 @@ describe BSNS do
111
119
  wuzz.species.should == "horse"
112
120
  end
113
121
 
122
+ it "should allow for embedded collections" do
123
+ fazz = Fizzle.load 'fazz'
124
+ fazz.cats.length.should == 2
125
+ fazz.cats[0].thing.should == 'whiskers'
126
+ fazz.cats[1].thing.should == 'hats'
127
+ end
128
+
114
129
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: bsns
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.2
4
+ version: 0.3.2
5
5
  prerelease:
6
6
  platform: ruby
7
7
  authors: