Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to create singleton in crystal #444

Closed
kostya opened this issue Feb 23, 2015 · 6 comments
Closed

how to create singleton in crystal #444

kostya opened this issue Feb 23, 2015 · 6 comments

Comments

@kostya
Copy link
Contributor

kostya commented Feb 23, 2015

in ruby:

class A
  class << self
    attr_accessor :bla
  end
end

A.bla = 10

how to to the same in crystal

@kostya kostya changed the title now to create singleton in crystal how to create singleton in crystal Feb 23, 2015
@kostya
Copy link
Contributor Author

kostya commented Feb 23, 2015

solved by:

class Aa
  property bla, some
end

A = Aa.new

A.bla = 10

@kostya kostya closed this as completed Feb 23, 2015
@asterite
Copy link
Member

You can also do:

class A
  def self.bla
    @@bla
  end

  def self.bla=(@@bla)
  end
end

A.bla = 10

@kostya
Copy link
Contributor Author

kostya commented Feb 23, 2015

is there macro for this?

class A
  self.property bla
end

@asterite
Copy link
Member

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.

@jhass
Copy link
Member

jhass commented Feb 23, 2015

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.

@rafapolo
Copy link

rafapolo commented Nov 16, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants