Skip to content

Instantly share code, notes, and snippets.

@kinopyo
Created August 30, 2012 13:36
Show Gist options
  • Save kinopyo/3528653 to your computer and use it in GitHub Desktop.
Save kinopyo/3528653 to your computer and use it in GitHub Desktop.
These are codes about instance_eval() in ruby: what is does, and how is it used in Rails ActiveRecord and ActiveSupport.
class ColumnDefinition < Struct.new(:base, :name, :type, :limit, :precision, :scale, :default, :null)
# Object#instance_eval()
p Object.instance_methods.grep(/instance_eval/)
# evaluates a block in the context of an someoneect
# (the block is evaluated with the receiver as self,
# so it can access the receiver's private methods and instance variables)
# it leaves all the other bindings alone
class Person
def initialize(name)
@name = name
end
private
def credit_card
"My credit card number is..."
end
end
outter_val = "Tom"
someone = Person.new("Bob")
someone.instance_eval do
# self became someone(an instance of Person)
self # => #<Person:0x007fa4e3843ca0 @name="Bob">
self == someone # => true
# access to the instance variable
@name # => "Bob"
# call the private method
credit_card # => "My credit card number is..."
# access the outter variable
@name = outter_val # => "Tom"
end
def change_column(table_name, column_name, type, options = {}) #:nodoc:
alter_table(table_name) do |definition|
include_default = options_include_default?(options)
definition[column_name].instance_eval do
self.type = type
self.limit = options[:limit] if options.include?(:limit)
self.default = options[:default] if include_default
self.null = options[:null] if options.include?(:null)
end
end
end
class Time
class << self
alias_method :_load_without_utc_flag, :_load
def _load(marshaled_time)
time = _load_without_utc_flag(marshaled_time)
time.instance_eval do
if defined?(@marshal_with_utc_coercion)
val = remove_instance_variable("@marshal_with_utc_coercion")
end
val ? utc : self
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment