Skip to content

Instantly share code, notes, and snippets.

@meltingice
Created May 6, 2014 15:28
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 meltingice/bbf55db4d2ec2d10866f to your computer and use it in GitHub Desktop.
Save meltingice/bbf55db4d2ec2d10866f to your computer and use it in GitHub Desktop.
Best way to set class level data and access from instance?
class MyClass < Base
option 'value'
def some_method
puts option
end
end
@meltingice
Copy link
Author

I'm currently doing:

class Base
  def self.option(value)
    define_method(:option) do
      value
    end
  end

  def option
    nil
  end
end

Which overwrites the instance method every time it's called to return the new value. This feels really hacky though. Any better ideas?

@kellysutton
Copy link

class Base
  cattr_accessor :option

  def option
    self.class.option || super
  end
end

Something like that, maybe?

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