Skip to content

Instantly share code, notes, and snippets.

@defvol
Created November 24, 2012 20:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save defvol/4141258 to your computer and use it in GitHub Desktop.
Save defvol/4141258 to your computer and use it in GitHub Desktop.
Makes any NSObject conform to the NSCoding protocol
# Makes any NSObject conform to the NSCoding protocol
# Authors:
# @rod_wilhelmy
# @cicloid
module Serializable
def attr_accessor_setters
methods.grep(/\w=:$/)
end
def initWithCoder(coder)
self.init
attr_accessor_setters.each do |method|
key = method.to_s.sub('=:', '')
self.send(method, coder.decodeObjectForKey(key))
end
self
end
def encodeWithCoder(coder)
attr_accessor_setters.each do |method|
key = method.to_s.sub('=:', '')
coder.encodeObject(self.send(key), forKey:key)
end
end
end
@defvol
Copy link
Author

defvol commented Nov 24, 2012

Usage:

class User
  include Serializable
  attr_accessor :id, :name, :avatar_url, :nickname, :email
end

@defvol
Copy link
Author

defvol commented Nov 30, 2012

Cool!
A module system for the C family: http://llvm.org/devmtg/2012-11/Gregor-Modules.pdf?=submit

@knoxjeffrey
Copy link

That is brilliant, although took me a while to understand exactly how it works! Didn't realise setters were returned as example_setter:= by the methods method

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment