Skip to content

Instantly share code, notes, and snippets.

@madwork
Last active December 14, 2015 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madwork/5110037 to your computer and use it in GitHub Desktop.
Save madwork/5110037 to your computer and use it in GitHub Desktop.
Various method to add dynamic accessors (getters/setters)

Various method to add dynamic accessors (getters/setters)

Make it yourself way

foo = Foo1.new
foo.build1 :a, :b
foo.a = 1
foo.a

foo = Foo1.new
foo.build2 :a, :b
foo.a = 1
foo.a

Open Struct way (only ruby 1.9)

foo = Foo2.new
foo.a = 1
foo.a

Struct way

foo = STRUCT.new
foo.a = 1
foo.a

Benchmark for fun on my extremly slow computer (@work)...

require 'benchmark'
require 'benchmark/ips'
load './instance_with_dynamic_accessor.rb'
Benchmark.ips do |x|
x.report("singleton_class") do
foo = Foo1.new
foo.build1 :a, :b
foo.a = 1
foo.a
end
x.report("send") do
foo = Foo1.new
foo.build2 :a, :b
foo.a = 1
foo.a
end
x.report("open_struct") do
foo = Foo2.new
foo.a = 1
foo.a
end
x.report("struct") do
struct = Struct.new :a, :b
foo = struct.new
foo.a = 1
foo.a
end
end
# Make it yourself
class Foo1
def build1(*args)
singleton_class.class_eval do
attr_accessor *args
end
end
def build2(*args)
self.class.__send__ :attr_accessor, *args
end
end
# OpenStruct
require 'ostruct'
class Foo2 < OpenStruct
end
# Struct
att = [:a, :b]
STRUCT = Struct.new *att
Calculating -------------------------------------
singleton_class 9595 i/100ms
send 9920 i/100ms
open_struct 5868 i/100ms
struct 7343 i/100ms
-------------------------------------------------
singleton_class 127811.0 (±7.2%) i/s - 642865 in 5.058452s
send 124758.9 (±17.2%) i/s - 615040 in 5.071965s
open_struct 68718.4 (±4.1%) i/s - 346212 in 5.046394s
struct 87365.2 (±15.9%) i/s - 425894 in 5.076300s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment