in ruby:
class A
class << self
attr_accessor :bla
end
end
A.bla = 10
how to to the same in crystal
solved by:
class Aa
property bla, some
end
A = Aa.new
A.bla = 10
You can also do:
class A
def self.bla
@@bla
end
def self.bla=(@@bla)
end
end
A.bla = 10
is there macro for this?
class A
self.property bla
end
Not yet. It would actually be nice to have the class << self thing, but only for classes (not for instances) and then be able to use the existing macros. The problem is that classes don't have instance variables right now... but they could be the same thing, maybe.
IMO it's not wise to allow class << self when you don't have the truly same meta-model as Ruby, it's only confusing. I'd just go for class_property.
Other general elegant singleton solution in Crystal can be,
class Config
property params = {} of Symbol => (String | Bool | Float64)
def initialize
@params[:logs] = false
@params[:simulate] = false
end
def self.params
self.instance.params
end
def self.instance
@@instance ||= new
end
end
While accessible and "dynamic" by any other classes as
Config.params[:value] = 7000.85