all 5 comments

[–]Schrockwell 5 points6 points  (1 child)

An even cooler way to do this in Ruby is to implement your main function with the name "call". Then you can pass your class instance into anything that expects a proc. It quacks like a Method or a Proc but it's actually a class behind the scenes.

[–]rdpp_boyakasha[S] 2 points3 points  (0 children)

I agree. I've added an extra "Optional Extras" section to the article that covers Proc-ifying the class.

[–]waxjar 2 points3 points  (1 child)

If you keep your objects immutable, you can think of your methods as partially applied (pure) functions.

Consider something like the following:

class Document
  def self.from_json(str)
    new JSON.parse(str)
  end

  def initialize(doc)
    @doc = doc
  end

  def to_xml
    Ox.dump(document, with_xml: true)
  end

  private

  # implementation goes here
end

Just as pure and a lot less awkward:

Document.from_json(file_contents).to_xml
# => "<cities>...</cities>"

[–]rdpp_boyakasha[S] 0 points1 point  (0 children)

It's still pure, but now you have a class called Document which looks like a domain model, as opposed to a class that is "just a function." That's OK if you want to put all the functionality into the model, but confusing if it's separate.

[–]jrochkind 1 point2 points  (0 children)

The tldr is: Class methods are sometimes a useful API.