meso_2600
meso_2600

Reputation: 2126

How properly call an instance method and class method afterwards

I would like to save some string in my database, but by using just one line without creating instance of the Object, like:

Secret.add('SuperSecret')

So I have the following class:

class Secret
  include MongoMapper::Document
  [some keys...]

def self.add(secret)
  if not secret.is_a? String
    return 'Not a string'
  end

  s = Secret.new(secret)
  s.save
end

But that doesnt look good...

Please don't tell me I can use MongoMapper validators, that's not the case here, it's more about writing guidelines.

Thank you

Upvotes: 0

Views: 52

Answers (2)

Kashyap
Kashyap

Reputation: 4796

you could use self.new instead of Secret.new. And since the add method is a class method, the self can be skipped. Something like this would work:

class Secret
  include MongoMapper::Document

  key :secret, String

  def self.add(secret_key)
    raise "Not a string" unless key.is_a?(String)

    s = new(secret: secret_key)
    s.save
  end
end

Upvotes: 0

SLD
SLD

Reputation: 659

class SecretTypeError < StandardError; end

def self.add(secret)
  unless secret.is_a?(String)
    raise SecretTypeError, "Expected type String, got #{secret.class}"
  end

  self.new(secret).save
end

Raise an error instead of returning a string, or at least return false so you can test for it. Alternatively use a string validator and alias your add method to new.

Upvotes: 1

Related Questions