Moyersy
Moyersy

Reputation: 74

Ruby object design for series of methods

I'm trying to parse a string from a mess ("SOME.String_With-bits.txt") into a clean string ("Some String With Bits") in Ruby. I'd like to be able to call a nice simple method and get the cleaned string - Eg. clean_string = NameParser::parse(messy_string)

I'm trying to do a nice testable design here, but I'm really struggling to come up with a structure (the actual parsing code is no problem). Parsing the string is quite complex and I'd like to separate out the stages. I've tried this:

class NameParser
  def self.parse(name)
    name = self.correct_case(name)
    name = self.correct_whitespace(name)
    name = self.remove_extension(name)
    return name
  end


  def self.correct_case(name) ....
  def self.correct_whitespace(name) ....
  def self.remove_extension(name) ....
end

It looks HORRIFIC. What can I do? Can anyone point me to a similar implementation somewhere on Github?

Upvotes: 1

Views: 55

Answers (2)

markijbema
markijbema

Reputation: 4055

To avoid programming so much classbased, and instead program more object based, You can remove all the self. methods, and make a convenience method self.parse if you like:

def self.parse string
  new.parse(string) 
end

Or create a parser with the string in the initialize. It depends a bit on how you use it exactly which feels best.

Upvotes: 1

KARASZI István
KARASZI István

Reputation: 31467

I think the following code could do that:

class Object
  def chain_methods(start_value, *methods)
    methods.inject(start_value) { |last, method| self.send(method, last) }
  end
end

And the usage:

NameParser.chain_methods(name, :correct_case, :correct_whitespace, :remove_extension)

Upvotes: 1

Related Questions