Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's how I'd implement the metaprogramming part that creates the accessor methods and sets them as attr_accessibles.</p> <p>I'm using YAML intead of XML just as a personal crusade. I even went ahead and implemented the unneeded serialization part just to nudge you towards YAML.</p> <pre><code>require 'yaml' require 'rubygems' require 'active_support' require 'active_record' module Yamlable def self.included m m.extend ClassMethods end module ClassMethods def add_yaml_fields *args write_inheritable_array(:yaml_fields, args) attr_accessor(*args) attr_accessible(*args) before_save :serialize_yaml_fields end end def serialize_yaml_fields self.yamlable_column = read_inheritable_attribute(:yaml_fields)\ .inject({}) { |h, a| h[a] = send(a); h }.to_yaml end def initialize(*args) super YAML::load(yamlable_column).each { |k, v| send("#{k}=", v) } end end class ParentModel &lt; ActiveRecord::Base include Yamlable add_yaml_fields :foo, :bar end class ChildModel &lt; ParentModel end # look, they're there: y ChildModel.read_inheritable_attribute(:yaml_fields) </code></pre> <p>Now, if you want to know why your particular code didn't work, you'll have to post more of it.</p> <hr> <p>I should probably expand a bit on class inheritable attributes. They are a bit like class variables, a bit like class instance variables.</p> <p>If you define an inheritable attribute in a class, all its subclasses will share it. But if you update said attribute in a child class, this child class copies the original attribute and updates it, so the updates are exclusive to it and don't affect other classes around it in the inheritance chain.</p> <p>With the normal <code>write_inheritable_attribute</code> method, setting it on a child class will simply override the value from the parent. With inheritable arrays and hashes, <code>write_inheritable_*</code> will concat / merge to the parent class's values. </p> <hr> <p>So, in practice, my <code>add_yaml_fields</code> works like this:</p> <pre><code>class Parent add_yaml_attributes :foo class Child1 &lt; Parent add_yaml_attributes :bar class Child2 &lt; Parent add_yaml_attributes :baz </code></pre> <p>With that, the yaml attributes for each class will be:</p> <ul> <li>Parent: foo</li> <li>Child1: foo, bar</li> <li>Child2: foo, baz</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload