Crystal: how to create singleton in crystal

Created on 23 Feb 2015  路  6Comments  路  Source: crystal-lang/crystal

in ruby:

class A
  class << self
    attr_accessor :bla
  end
end

A.bla = 10

how to to the same in crystal

All 6 comments

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
Was this page helpful?
0 / 5 - 0 ratings

Related issues

RX14 picture RX14  路  3Comments

jhass picture jhass  路  3Comments

Papierkorb picture Papierkorb  路  3Comments

nabeelomer picture nabeelomer  路  3Comments

will picture will  路  3Comments