Class: Object
- Inherits:
- BasicObject
- Includes:
- InstanceExecMethods
- Defined in:
- lib/gems/activesupport-2.2.2/lib/active_support/vendor/builder-2.1.2/blankslate.rb,
lib/mack-facets/extensions/object.rb,
lib/gems/extlib-0.9.9/lib/extlib/blank.rb,
lib/gems/extlib-0.9.9/lib/extlib/object.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/blank.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/duplicable.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/misc.rb,
lib/gems/activesupport-2.2.2/lib/active_support/json/encoders/object.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/kernel/agnostics.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/extending.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/metaclass.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/conversions.rb,
lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/instance_variables.rb
Overview
Same as above, except in Object.
Defined Under Namespace
Modules: InstanceExecMethods
Class Method Summary collapse
- .blank_slate_method_added ⇒ Object
- .find_hidden_method(name) ⇒ Object
-
.method_added(name) ⇒ Object
Detect method additions to Object and remove them in the BlankSlate class.
-
.needs_method(meth) ⇒ Object
Uses
define_method
to create an empty for the method parameter defined.
Instance Method Summary collapse
-
#`(command) ⇒ Object
Makes backticks behave (somewhat more) similarly on all platforms.
-
#acts_like?(duck) ⇒ Boolean
A duck-type assistant method.
-
#blank? ⇒ Boolean
An object is blank if it’s false, empty, or a whitespace string.
-
#class_eval(*args, &block) ⇒ Object
If class_eval is called on an object, add those methods to its metaclass.
-
#class_parents ⇒ Object
See Class parents for more information.
-
#copy_instance_variables_from(object, exclude = []) ⇒ Object
Copies the instance variables of
object
intoself
. - #define_instance_method(sym, &block) ⇒ Object
-
#duplicable? ⇒ Boolean
Can you safely .dup this object? False for nil, false, true, symbols, and numbers; true otherwise.
-
#extend_with_included_modules_from(object) ⇒ Object
:nodoc:.
-
#extended_by ⇒ Object
:nodoc:.
-
#full_const_get(name) ⇒ Object
The constant corresponding to the name.
-
#full_const_set(name, value) ⇒ Object
The constant corresponding to the name.
-
#in?(arrayish, *more) ⇒ TrueClass, FalseClass
True if the object is included in arrayish (+ more).
-
#instance_exec(*args, &block) ⇒ Object
Evaluate the block with the given arguments within the context of this object, so self is set to the method receiver.
-
#instance_values ⇒ Object
Returns a hash that maps instance variable names without “@” to their corresponding values.
- #instance_variable_defined?(variable) ⇒ Boolean
-
#ivar_cache(var_name = nil, &block) ⇒ Object
ivar_cache allows you to cache the results of the block into an instance variable in a class, and then will serve up that instance variable the next time you call that method again.
- #ivar_cache_clear(var_name = nil, &block) ⇒ Object
-
#make_module(str) ⇒ NilClass
Defines module from a string name (e.g. Foo::Bar::Baz) If module already exists, no exception raised.
-
#meta_class ⇒ Class
Extracts the singleton class, so that metaprogramming can be done on it.
-
#metaclass ⇒ Object
Get object’s meta (ghost, eigenclass, singleton) class.
-
#namespaces ⇒ Object
Returns the namespaces for a particular object.
-
#present? ⇒ Boolean
An object is present if it’s not blank.
-
#print_methods ⇒ Object
Prints out the methods associated with this object in alphabetical order.
-
#quacks_like?(duck) ⇒ TrueClass, FalseClass
True if the object quacks like duck.
-
#remove_subclasses_of(*superclasses) ⇒ Object
:nodoc:.
-
#returning(value) {|value| ... } ⇒ Object
Returns
value
after yieldingvalue
to the block. -
#running_time(message = "", logger = nil) ⇒ Object
This prints out running time for the block provided.
-
#safely_include_module(*modules) ⇒ Object
Includes a module into the current Class, and changes all the module’s public methods to protected.
-
#send_with_chain(methods, *args) ⇒ Object
This method will call send to all the methods defined on the previous method.
-
#to_json(options = {}) ⇒ Object
Dumps object in JSON (JavaScript Object Notation).
-
#to_param ⇒ Object
Alias of
to_s
. -
#to_query(key) ⇒ Object
Converts an object into a string suitable for use as a URL query string, using the given
key
as the param name. -
#try_dup ⇒ Object
Override this in a child if it cannot be dup’ed.
-
#with_options(options) {|ActiveSupport::OptionMerger.new(self, options)| ... } ⇒ Object
An elegant way to factor duplication out of options passed to a series of method calls.
Class Method Details
.blank_slate_method_added ⇒ Object
79 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/vendor/builder-2.1.2/blankslate.rb', line 79 alias_method :blank_slate_method_added, :method_added |
.find_hidden_method(name) ⇒ Object
90 91 92 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/vendor/builder-2.1.2/blankslate.rb', line 90 def find_hidden_method(name) nil end |
.method_added(name) ⇒ Object
Detect method additions to Object and remove them in the BlankSlate class.
83 84 85 86 87 88 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/vendor/builder-2.1.2/blankslate.rb', line 83 def method_added(name) result = blank_slate_method_added(name) return result if self != Object BlankSlate.hide(name) result end |
.needs_method(meth) ⇒ Object
Uses define_method
to create an empty for the method parameter defined. That method will then raise MethodNotImplemented. This is useful for creating interfaces and you want to stub out methods that others need to implement.
63 64 65 66 67 |
# File 'lib/mack-facets/extensions/object.rb', line 63 def self.needs_method(meth) define_method(meth) do raise NoMethodError.new("The interface you are using requires you define the following method '#{meth}'") end end |
Instance Method Details
#`(command) ⇒ Object
Makes backticks behave (somewhat more) similarly on all platforms. On win32 ‘nonexistent_command` raises Errno::ENOENT; on Unix, the spawned shell prints a message to stderr and sets $?. We emulate Unix on the former but not the latter.
6 7 8 9 10 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/kernel/agnostics.rb', line 6 def `(command) #:nodoc: super rescue Errno::ENOENT => e STDERR.puts "#$0: #{e}" end |
#acts_like?(duck) ⇒ Boolean
A duck-type assistant method. For example, Active Support extends Date to define an acts_like_date? method, and extends Time to define acts_like_time?. As a result, we can do “x.acts_like?(:time)” and “x.acts_like?(:date)” to do duck-type-safe comparisons, since classes that we want to act like Time simply need to define an acts_like_time? method.
71 72 73 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/misc.rb', line 71 def acts_like?(duck) respond_to? "acts_like_#{duck}?" end |
#blank? ⇒ Boolean
An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil
, [], and {} are blank.
This simplifies
if !address.nil? && !address.empty?
to
if !address.blank?
12 13 14 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/blank.rb', line 12 def blank? nil? || (respond_to?(:empty?) && empty?) end |
#class_eval(*args, &block) ⇒ Object
If class_eval is called on an object, add those methods to its metaclass
10 11 12 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/metaclass.rb', line 10 def class_eval(*args, &block) .class_eval(*args, &block) end |
#class_parents ⇒ Object
See Class parents for more information.
50 51 52 |
# File 'lib/mack-facets/extensions/object.rb', line 50 def class_parents self.class.parents end |
#copy_instance_variables_from(object, exclude = []) ⇒ Object
Copies the instance variables of object
into self
.
Instance variable names in the exclude
array are ignored. If object
responds to protected_instance_variables
the ones returned are also ignored. For example, Rails controllers implement that method.
In both cases strings and symbols are understood, and they have to include the at sign.
class C
def initialize(x, y, z)
@x, @y, @z = x, y, z
end
def protected_instance_variables
%w(@z)
end
end
a = C.new(0, 1, 2)
b = C.new(3, 4, 5)
a.copy_instance_variables_from(b, [:@y])
# a is now: @x = 3, @y = 1, @z = 2
68 69 70 71 72 73 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/instance_variables.rb', line 68 def copy_instance_variables_from(object, exclude = []) #:nodoc: exclude += object.protected_instance_variables if object.respond_to? :protected_instance_variables vars = object.instance_variables.map(&:to_s) - exclude.map(&:to_s) vars.each { |name| instance_variable_set(name, object.instance_variable_get(name)) } end |
#define_instance_method(sym, &block) ⇒ Object
3 4 5 6 7 8 |
# File 'lib/mack-facets/extensions/object.rb', line 3 def define_instance_method(sym, &block) mod = Module.new do define_method(sym, &block) end self.extend mod end |
#duplicable? ⇒ Boolean
Can you safely .dup this object? False for nil, false, true, symbols, and numbers; true otherwise.
4 5 6 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/duplicable.rb', line 4 def duplicable? true end |
#extend_with_included_modules_from(object) ⇒ Object
:nodoc:
50 51 52 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/extending.rb', line 50 def extend_with_included_modules_from(object) #:nodoc: object.extended_by.each { |mod| extend mod } end |
#extended_by ⇒ Object
:nodoc:
45 46 47 48 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/extending.rb', line 45 def extended_by #:nodoc: ancestors = class << self; ancestors end ancestors.select { |mod| mod.class == Module } - [ Object, Kernel ] end |
#full_const_get(name) ⇒ Object
Returns The constant corresponding to the name.
64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 64 def full_const_get(name) list = name.split("::") list.shift if list.first.blank? obj = self list.each do |x| # This is required because const_get tries to look for constants in the # ancestor chain, but we only want constants that are HERE obj = obj.const_defined?(x) ? obj.const_get(x) : obj.const_missing(x) end obj end |
#full_const_set(name, value) ⇒ Object
Returns The constant corresponding to the name.
80 81 82 83 84 85 86 87 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 80 def full_const_set(name, value) list = name.split("::") toplevel = list.first.blank? list.shift if toplevel last = list.pop obj = list.empty? ? Object : Object.full_const_get(list.join("::")) obj.const_set(last, value) if obj && !obj.const_defined?(last) end |
#in?(arrayish, *more) ⇒ TrueClass, FalseClass
Returns True if the object is included in arrayish (+ more).
147 148 149 150 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 147 def in?(arrayish,*more) arrayish = more.unshift(arrayish) unless more.empty? arrayish.include?(self) end |
#instance_exec(*args, &block) ⇒ Object
Evaluate the block with the given arguments within the context of this object, so self is set to the method receiver.
From Mauricio’s eigenclass.org/hiki/bounded+space+instance_exec
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/extending.rb', line 63 def instance_exec(*args, &block) begin old_critical, Thread.critical = Thread.critical, true n = 0 n += 1 while respond_to?(method_name = "__instance_exec#{n}") InstanceExecMethods.module_eval { define_method(method_name, &block) } ensure Thread.critical = old_critical end begin send(method_name, *args) ensure InstanceExecMethods.module_eval { remove_method(method_name) } rescue nil end end |
#instance_values ⇒ Object
Returns a hash that maps instance variable names without “@” to their corresponding values. Keys are strings both in Ruby 1.8 and 1.9.
class C
def initialize(x, y)
@x, @y = x, y
end
end
C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
19 20 21 22 23 24 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/instance_variables.rb', line 19 def instance_values #:nodoc: instance_variables.inject({}) do |values, name| values[name.to_s[1..-1]] = instance_variable_get(name) values end end |
#instance_variable_defined?(variable) ⇒ Boolean
158 159 160 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 158 def instance_variable_defined?(variable) instance_variables.include?(variable.to_s) end |
#ivar_cache(var_name = nil, &block) ⇒ Object
ivar_cache allows you to cache the results of the block into an instance variable in a class, and then will serve up that instance variable the next time you call that method again.
old way:
def show_page_link
unless @show_page_link # check if instance variable exists
# if the instance variable doesn't exist let's do some work and assign it to the instance variable.
@show_page_link = link_to("show", some_url(:id => self.id, :foo => , etc... => etc))
end
@show_page_link # now return the instance variable
end
new way:
def show_page_link
ivar_cache do
link_to("show", some_url(:id => self.id, :foo => , etc... => etc))
end
end
this does everything the old way did, but it is much cleaner, and a lot less code! in case you’re wondering it caches the result, by default, to an instance variable named after the method, so in our above example the instance variable would be name, @show_page_link
. this can be overridden like such:
def show_page_link
ivar_cache("foo_var") do
link_to("show", some_url(:id => self.id, :foo => , etc... => etc))
end
end
now it will cache it to @foo_var
136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/mack-facets/extensions/object.rb', line 136 def ivar_cache(var_name = nil, &block) if var_name.nil? call = caller[0] var_name = call[(call.index('`')+1)...call.index("'")] end var = instance_variable_get("@#{var_name}") unless var return instance_variable_set("@#{var_name}", yield) if block_given? end instance_variable_get("@#{var_name}") end |
#ivar_cache_clear(var_name = nil, &block) ⇒ Object
148 149 150 151 152 153 154 155 |
# File 'lib/mack-facets/extensions/object.rb', line 148 def ivar_cache_clear(var_name = nil, &block) if var_name.nil? call = caller[0] var_name = call[(call.index('`')+1)...call.index("'")] end remove_instance_variable("@#{var_name}") #rescue yield if block_given? end |
#make_module(str) ⇒ NilClass
Defines module from a string name (e.g. Foo::Bar::Baz) If module already exists, no exception raised.
95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 95 def make_module(str) mod = str.split("::") current_module = self mod.each do |x| unless current_module.const_defined?(x) current_module.class_eval "module #{x}; end" end current_module = current_module.const_get(x) end current_module end |
#meta_class ⇒ Class
Extracts the singleton class, so that metaprogramming can be done on it.
59 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 59 def () class << self; self end end |
#metaclass ⇒ Object
Get object’s meta (ghost, eigenclass, singleton) class
3 4 5 6 7 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/metaclass.rb', line 3 def class << self self end end |
#namespaces ⇒ Object
Returns the namespaces for a particular object.
Examples:
Animals::Dog::Poodle.new.namespaces # => ["Animals", "Dog"]
161 162 163 164 165 166 167 168 169 |
# File 'lib/mack-facets/extensions/object.rb', line 161 def namespaces ivar_cache("object_namespaces") do nss = [] full_name = self.class.name.to_s nss = full_name.split("::") nss.pop nss end end |
#present? ⇒ Boolean
An object is present if it’s not blank.
17 18 19 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/blank.rb', line 17 def present? !blank? end |
#print_methods ⇒ Object
Prints out the methods associated with this object in alphabetical order.
23 24 25 26 27 28 |
# File 'lib/mack-facets/extensions/object.rb', line 23 def print_methods m = "----- #{self} (methods) -----\n" m << methods.sort.join("\n") puts m m end |
#quacks_like?(duck) ⇒ TrueClass, FalseClass
The behavior of the method depends on the type of duck as follows:
- Symbol
-
Check whether the object respond_to?(duck).
- Class
-
Check whether the object is_a?(duck).
- Array
-
Check whether the object quacks_like? at least one of the options in the array.
Returns True if the object quacks like duck.
119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 119 def quacks_like?(duck) case duck when Symbol self.respond_to?(duck) when Class self.is_a?(duck) when Array duck.any? {|d| self.quacks_like?(d) } else false end end |
#remove_subclasses_of(*superclasses) ⇒ Object
:nodoc:
2 3 4 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/extending.rb', line 2 def remove_subclasses_of(*superclasses) #:nodoc: Class.remove_class(*subclasses_of(*superclasses)) end |
#returning(value) {|value| ... } ⇒ Object
Returns value
after yielding value
to the block. This simplifies the process of constructing an object, performing work on the object, and then returning the object from a method. It is a Ruby-ized realization of the K combinator, courtesy of Mikael Brockman.
Examples
# Without returning
def foo
values = []
values << "bar"
values << "baz"
return values
end
foo # => ['bar', 'baz']
# returning with a local variable
def foo
returning values = [] do
values << 'bar'
values << 'baz'
end
end
foo # => ['bar', 'baz']
# returning with a block argument
def foo
returning [] do |values|
values << 'bar'
values << 'baz'
end
end
foo # => ['bar', 'baz']
38 39 40 41 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/misc.rb', line 38 def returning(value) yield(value) value end |
#running_time(message = "", logger = nil) ⇒ Object
This prints out running time for the block provided. This is great for things like Rake tasks, etc… where you would like to know how long it, or a section of it took to run.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/mack-facets/extensions/object.rb', line 72 def running_time( = "", logger = nil) s_time = Time.now s = "---Starting at #{s_time}---" puts s logger.info s unless logger.nil? yield if block_given? e_time = Time.now e = "---Ending at #{e_time}---" puts e logger.info e unless logger.nil? secs = e_time - s_time if secs < 60 x = "Running time #{secs} seconds." else x = "Running time roughly #{secs/60} minutes [#{secs} seconds]" end x += " [MESSAGE]: #{}" unless .blank? puts x logger.info x unless logger.nil? end |
#safely_include_module(*modules) ⇒ Object
Includes a module into the current Class, and changes all the module’s public methods to protected.
Example:
class FooController
safely_include_module(MyCoolUtils, MyOtherModule)
end
16 17 18 19 20 |
# File 'lib/mack-facets/extensions/object.rb', line 16 def safely_include_module(*modules) [modules].flatten.each do |mod| mod.include_safely_into(self) end end |
#send_with_chain(methods, *args) ⇒ Object
This method will call send to all the methods defined on the previous method.
Example:
Fruit.send_with_chain([:new, :get_citrus, :get_orange, :class]) # => Orange
This would be the equivalent:
Fruit.new.get_citrus.get_orange.class
100 101 102 103 104 |
# File 'lib/mack-facets/extensions/object.rb', line 100 def send_with_chain(methods, *args) obj = self [methods].flatten.each {|m| obj = obj.send(m, *args)} obj end |
#to_json(options = {}) ⇒ Object
Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.
3 4 5 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/json/encoders/object.rb', line 3 def to_json( = {}) ActiveSupport::JSON.encode(instance_values, ) end |
#to_param ⇒ Object
Alias of to_s
.
56 57 58 |
# File 'lib/mack-facets/extensions/object.rb', line 56 def to_param self.to_s end |
#to_query(key) ⇒ Object
Converts an object into a string suitable for use as a URL query string, using the given key
as the param name.
Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.
11 12 13 |
# File 'lib/gems/activesupport-2.2.2/lib/active_support/core_ext/object/conversions.rb', line 11 def to_query(key) "#{CGI.escape(key.to_s)}=#{CGI.escape(to_param.to_s)}" end |
#try_dup ⇒ Object
Override this in a child if it cannot be dup’ed
135 136 137 |
# File 'lib/gems/extlib-0.9.9/lib/extlib/object.rb', line 135 def try_dup self.dup end |
#with_options(options) {|ActiveSupport::OptionMerger.new(self, options)| ... } ⇒ Object
An elegant way to factor duplication out of options passed to a series of method calls. Each method called in the block, with the block variable as the receiver, will have its options merged with the default options
hash provided. Each method called on the block variable must take an options hash as its final argument.
:order => 'created_at', :class_name => 'Comment' do |post|
post.has_many :comments, :conditions => ['approved = ?', true], :dependent => :delete_all
post.has_many :unapproved_comments, :conditions => ['approved = ?', false]
post.has_many :all_comments
end
Can also be used with an explicit receiver:
map. :controller => "people" do |people|
people.connect "/people", :action => "index"
people.connect "/people/:id", :action => "show"
end
45 46 47 |
# File 'lib/mack-facets/extensions/object.rb', line 45 def () yield Mack::Utils::OptionMerger.new(self, ) end |