0

I always have a brain cramp when it comes to this. I'm creating a module to mix in to model-like classes but it needs to keep exactly one copy of serializable attributes per class. So here is the code (that doesn't work).

module Checkin module Model def self.included(base) base.extend(ClassMethods) end @@serialiable_attrs = [] <== really not the right place module ClassMethods def serializable(*attrs) attrs.each{|attr| @@serializable_attrs << attr} # Is this @@ or just @? end end def serialize! @@serializable_attrs.each{|a| do_something_with(a)} # <== Will this work? end end end class Person include Checkin::Model serializable :first_name, :original_name, :last_name, :checked_in, :people_attending # etc., etc. end 

What I'm wrangling with are two things:

  1. How to define my mix-in such that a class variable magically springs into existence; and
  2. How to access that variable both in my ClassMethods module and in the (for lack of a better term) instance methods part of the module.

Note that I've settled on a mix-in technique rather than inheritance because I will have Validatable, Persistable, Serializable and so on. Also, I know there are all sorts of validation and persistence layers available that are well tested and heavily used. This is a different beast and I really should know who to do this in my sleep, right?

Any Ruby wizards who can help me understand how to do this or suggest a different direction to approach this problem from, I appreciate the help!

1 Answer 1

1

Try removing the class variable, and adding this to the module ClassMethod:

def self.extended(klass) klass.instance_variable_set("@serializable_attrs", []) end 

And changing the double-@ to single in serializable. And change serialize! to this:

self.class.instance_variable_get("@serializable_attrs").each{|a| do_something_with(a)} 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I was part way there when I thought, "this is too ugly." I'm happy to see it's just my imagination and that this is right.
@SteveRoss: Glad I could help. Just work out the value of self in your head. That's the key to Ruby metaprograming. Ruby never preforms any black magic, remember that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.