class_attr 0.1.0 → 0.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (2) hide show
  1. data/lib/class_attr.rb +36 -0
  2. metadata +3 -3
data/lib/class_attr.rb CHANGED
@@ -168,13 +168,49 @@ class Class
168
168
 
169
169
  private
170
170
 
171
+ # Non-inheritable attrs won't get any starting value, even if it has been set
172
+ # on a superclass so we need to save the value and set them when the class is
173
+ # inherited.
174
+ #
175
+ # @param key [Symbol]
176
+ # @param value [Object]
177
+ #
178
+ def register_default(key, value)
179
+ registered_defaults[key] = value
180
+ end
181
+
182
+ def registered_defaults
183
+ @registered_defaults ||= {}
184
+ end
185
+
186
+ def inherited_with_attrs(klass)
187
+ inherited_without_attrs(klass) if respond_to?(:inherited_without_attrs)
188
+ if registered_defaults
189
+ new_attrs = registered_defaults.inject({}) do |a, (k, v)|
190
+ a.update(k => (v.dup rescue v))
191
+ end
192
+ else
193
+ new_attrs = {}
194
+ end
195
+
196
+ new_attrs.each do |k, v|
197
+ klass.instance_variable_set("@#{k}", v)
198
+ end
199
+ end
200
+ alias inherited_without_attrs inherited
201
+ alias inherited inherited_with_attrs
202
+
171
203
  # @param args [Array]
172
204
  # @return [Array[Array, Object]]
173
205
  #
174
206
  def separate_argument_list_and_default(args)
175
207
  if args.size == 1 && args.first.is_a?(Hash)
208
+ register_default(args.first.keys[0], args.first.values[0])
176
209
  [[args.first.keys[0]], args.first.values[0]]
177
210
  elsif args.last.is_a?(Hash)
211
+ args[0..-2].each do |arg|
212
+ register_default(arg, args.last[:default])
213
+ end
178
214
  [args[0..-2], args.last[:default]]
179
215
  else
180
216
  [args, nil]
metadata CHANGED
@@ -5,8 +5,8 @@ version: !ruby/object:Gem::Version
5
5
  segments:
6
6
  - 0
7
7
  - 1
8
- - 0
9
- version: 0.1.0
8
+ - 1
9
+ version: 0.1.1
10
10
  platform: ruby
11
11
  authors:
12
12
  - Joshua Hawxwell
@@ -14,7 +14,7 @@ autorequire:
14
14
  bindir: bin
15
15
  cert_chain: []
16
16
 
17
- date: 2011-01-29 00:00:00 +00:00
17
+ date: 2011-01-30 00:00:00 +00:00
18
18
  default_executable:
19
19
  dependencies: []
20
20