Skip to content

Instantly share code, notes, and snippets.

@jozip
Created March 17, 2011 19:42
Show Gist options
  • Save jozip/874981 to your computer and use it in GitHub Desktop.
Save jozip/874981 to your computer and use it in GitHub Desktop.
class Object
def define_eigenmethod(m, &b)
(class << self; self end).send(:define_method, m, &b)
end
end
def Binary(ps)
Class.new do
define_eigenmethod(:unit) do |unit = nil, &b|
unit || b ? @unit = unit || b : @unit || :to_i
end
define_method(:to_binary) do
u = self.class.unit
if u.is_a?(Array)
u.map { |x| instance_variable_get("@#{x.to_s}").to_binary }.join
else
[u.is_a?(Proc) ? u.call : self.send(u)].pack(self.class.ps)
end
end
define_eigenmethod(:new_from_binary) { |bin| new(*bin.unpack(self.ps)) }
define_eigenmethod(:ps) { ps.is_a?(Array) ? ps.map(&:ps).join : ps }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment