lib/surrounded/context.rb in surrounded-0.3.1 vs lib/surrounded/context.rb in surrounded-0.4.0
- old
+ new
@@ -1,9 +1,20 @@
require 'set'
require 'surrounded/context/role_map'
-require 'redcard'
+# Some features are only available in versions of Ruby
+# where this method is true
+def module_method_rebinding?
+ return @__module_method_rebinding__ if defined?(@__module_method_rebinding__)
+ sample_method = Enumerable.instance_method(:to_a)
+ @__module_method_rebinding__ = begin
+ !!sample_method.bind(Object.new)
+ rescue TypeError
+ false
+ end
+end
+
module Surrounded
module Context
def self.extended(base)
base.send(:include, InstanceMethods)
base.singleton_class.send(:alias_method, :setup, :initialize)
@@ -15,13 +26,15 @@
def self.default_role_type=(type)
@default_role_type = type
end
- def new(*)
- instance = super
- instance.instance_variable_set('@__apply_role_policy', __apply_role_policy)
+ def new(*args, &block)
+ instance = allocate
+ instance.send(:preinitialize)
+ instance.send(:initialize, *args, &block)
+ instance.send(:postinitialize)
instance
end
def triggers
@triggers.dup
@@ -61,11 +74,11 @@
wrapper_name = name.to_s.gsub(/(?:^|_)([a-z])/){ $1.upcase }
klass = private_const_set(wrapper_name, Class.new(SimpleDelegator, &block))
klass.send(:include, Surrounded)
end
- if RedCard.check '2.0'
+ if module_method_rebinding?
def interface(name, &block)
class_basename = name.to_s.gsub(/(?:^|_)([a-z])/){ $1.upcase }
interface_name = class_basename + 'Interface'
behavior = private_const_set(interface_name, Module.new(&block))
@@ -88,14 +101,14 @@
def initialize(*setup_args)
private_attr_reader(*setup_args)
class_eval "
def initialize(#{setup_args.join(',')})
- @__apply_role_policy = :#{__apply_role_policy}
+ preinitialize
arguments = method(__method__).parameters.map{|arg| eval(arg[1].to_s) }
map_roles(#{setup_args}.zip(arguments))
- apply_roles if __apply_role_policy == :initialize
+ postinitialize
end
"
end
def private_attr_reader(*method_names)
@@ -143,9 +156,17 @@
def triggers
self.class.triggers
end
private
+
+ def preinitialize
+ @__apply_role_policy = self.class.send(:__apply_role_policy)
+ end
+
+ def postinitialize
+ apply_roles if __apply_role_policy == :initialize
+ end
def role_map
@role_map ||= RoleMap.new
end
\ No newline at end of file