Class: Object

Inherits:
BasicObject
Defined in:
lib/garcon/core_ext/object.rb

Overview

Author: Stefano Harding <[email protected]> License: Apache License, Version 2.0 Copyright: © 2014-2015 Stefano Harding

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

Returns true if the object is nil or empty (if applicable)

Examples:

[].blank?         # =>  true
[1].blank?        # =>  false
[nil].blank?      # =>  false

Returns:



30
31
32
# File 'lib/garcon/core_ext/object.rb', line 30

def blank?
  nil? || (respond_to?(:empty?) && empty?)
end

#clone?Boolean

Returns:



137
# File 'lib/garcon/core_ext/object.rb', line 137

def clone? ; true ; end

#dup!Object

Override this in a child class if it cannot be dup’ed.

obj1 = Object.new
obj2 = obj1.dup!
obj2.equal?(obj1)    #=> false

Returns:



117
118
119
# File 'lib/garcon/core_ext/object.rb', line 117

def dup!
  dup
end

#dup?Object

Can you safely call #dup on this object?

Returns ‘false` for `nil`, `false`, `true`, symbols, and numbers; `true` otherwise.

Returns:



136
# File 'lib/garcon/core_ext/object.rb', line 136

def dup?   ; true ; end

#full_const_get(name) ⇒ Object

Returns The constant corresponding to the name.

Parameters:

  • name (String)

    The name of the constant to get, e.g. “Garcon::Check”.

Returns:

  • (Object)

    The constant corresponding to the name.



208
209
210
211
212
213
214
215
216
# File 'lib/garcon/core_ext/object.rb', line 208

def full_const_get(name)
  list = name.split('::')
  list.shift if list.first.blank?
  obj = self
  list.each do |x|
    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.

Parameters:

  • name (String)

    The name of the constant to get, e.g. “Garcon::Check”.

  • value (Object)

    The value to assign to the constant.

Returns:

  • (Object)

    The constant corresponding to the name.



227
228
229
230
231
232
233
234
# File 'lib/garcon/core_ext/object.rb', line 227

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) ⇒ Boolean

Returns True if the object is included in arrayish (+ more).

Examples:

1.in?() # => true

1.in?(1,2,3) # => true

Parameters:

  • arrayish (#include?)

    Container to check, to see if it includes the object.

  • *more (Array)

    additional args, will be flattened into arrayish

Returns:

  • (Boolean)

    True if the object is included in arrayish (+ more)



295
296
297
298
# File 'lib/garcon/core_ext/object.rb', line 295

def in?(arrayish, *more)
  arrayish = more.unshift(arrayish) unless more.empty?
  arrayish.include?(self)
end

#itselfObject

An identity method that provides access to an object’s ‘self’.

Example

[1,2,3,4,5,1,2,2,3].group_by(&:itself)
#=> {1=>[1, 1], 2=>[2, 2, 2], 3=>[3, 3], 4=>[4], 5=>[5]}


105
106
107
# File 'lib/garcon/core_ext/object.rb', line 105

def itself
  self
end

#make_module(string) ⇒ nil

Defines module from a string name (e.g. Foo::Bar::Baz). If module already exists, no exception raised.

Parameters:

  • name (String)

    The name of the full module name to make

Returns:

  • (nil)


244
245
246
247
248
249
250
251
252
253
254
# File 'lib/garcon/core_ext/object.rb', line 244

def make_module(string)
  current_module = self
  string.split('::').each do |part|
    current_module = if current_module.const_defined?(part)
      current_module.const_get(part)
    else
      current_module.const_set(part, Module.new)
    end
  end
  current_module
end

#meta_classClass

Extracts the singleton class, so that metaprogramming can be done on it.

Examples:

Setup
class MyString < String; end

MyString.instance_eval do
  define_method :foo do
    puts self
  end
end

MyString.meta_class.instance_eval do
  define_method :bar do
    puts self
  end
end

def String.add_meta_var(var)
  self.meta_class.instance_eval do
    define_method var do
      puts "HELLO"
    end
  end
end
MyString.new("Hello").foo # => "Hello"
MyString.new("Hello").bar
  # => NoMethodError: undefined method `bar' for "Hello":MyString
MyString.foo
  # => NoMethodError: undefined method `foo' for MyString:Class
MyString.bar
  # => MyString
String.bar
  # => NoMethodError: undefined method `bar' for String:Class
MyString.add_meta_var(:x)
MyString.x # => HELLO

Returns:

  • (Class)

    The meta class.



200
# File 'lib/garcon/core_ext/object.rb', line 200

def meta_class() class << self; self end end

#object_state(data = nil) ⇒ Object

Get or set state of object. You can think of #object_state as an in-code form of marshalling.

class StateExample
  attr_reader :a, :b
  def initialize(a,b)
    @a, @b = a, b
  end
end

obj = StateExample.new(1,2)
obj.a  #=> 1
obj.b  #=> 2

obj.object_state  #=> {:a=>1, :b=>2}

obj.object_state(:a=>3, :b=>4)
obj.a  #=> 3
obj.b  #=> 4

For most object’s this is essentially the same as ‘instance.to_h`. But for data structures like Array and Hash it returns a snapshot of their contents, not the state of their instance variables.



324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/garcon/core_ext/object.rb', line 324

def object_state(data = nil)
  if data
    instance_variables.each do |iv|
      name = iv.to_s.sub(/^[@]/, '').to_sym
      instance_variable_set(iv, data[name])
    end
  else
    data = {}
    instance_variables.each do |iv|
      name = iv.to_s.sub(/^[@]/, '').to_sym
      data[name] = instance_variable_get(iv)
    end
    data
  end
end

#present?Boolean

Returns true if the object is NOT nil or empty

Examples:

[].present?         # =>  false
[1].present?        # =>  true
[nil].present?      # =>  true

Returns:



43
44
45
# File 'lib/garcon/core_ext/object.rb', line 43

def present?
  !blank?
end

#quacks_like?(duck) ⇒ Boolean

Note:

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 a duck.

Parameters:

  • duck (Symbol, Class, Array)

    The thing to compare the object to.

Returns:

  • (Boolean)

    True if the object quacks like a duck.



269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/garcon/core_ext/object.rb', line 269

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

#try(*a, &b) ⇒ Object

Note:

‘try` is defined on `Object`. Therefore, it won’t work with instances of classes that do not have ‘Object` among their ancestors, like direct subclasses of `BasicObject`.

Invokes the public method whose name goes as first argument just like ‘public_send` does, except that if the receiver does not respond to it the call returns `nil` rather than raising an exception.

Parameters:

Returns:



62
63
64
# File 'lib/garcon/core_ext/object.rb', line 62

def try(*a, &b)
  try!(*a, &b) if a.empty? || respond_to?(a.first)
end

#try!(*a, &b) ⇒ Object

Same as #try, but will raise a NoMethodError exception if the receiver is not ‘nil` and does not implement the tried method.

Returns:

Raises:

  • NoMethodError If the receiver is not ‘nil` and does not implement the tried method.



74
75
76
77
78
79
80
81
82
83
84
# File 'lib/garcon/core_ext/object.rb', line 74

def try!(*a, &b)
  if a.empty? && block_given?
    if b.arity.zero?
      instance_eval(&b)
    else
      yield self
    end
  else
    public_send(*a, &b)
  end
end

#try_call(*args) ⇒ Object

If receiver is callable, calls it and returns result. If not, just returns receiver itself.

Returns:



91
92
93
94
95
96
97
# File 'lib/garcon/core_ext/object.rb', line 91

def try_call(*args)
  if self.respond_to?(:call)
    self.call(*args)
  else
    self
  end
end

#try_dupObject

Alternative name for #dup!

Returns:



125
126
127
# File 'lib/garcon/core_ext/object.rb', line 125

def try_dup
  dup!
end