Nick Ginanto
Nick Ginanto

Reputation: 32130

using helper methods in model

by helper methods I mean methods that help me, not methods in the helper files

I have a class method User.make_from_file and inside I have pretty ugly logic. I want to seperate it to methods but for some reason it doesn't work

class User

...

def self.make_from_file(filename)

some logic

User.new(read_attr_from_file(filename))

end

  private

  def read_attr_from_file(filename)
    some logic
  end

end

but I get

NoMethodError: undefined method `read_attr_from_file' for #<Class:0x007fa4d4b4b290>
from /Users/guy/.rvm/gems/ruby-2.1.1/gems/activerecord-4.0.5/lib/active_record/dynamic_matchers.rb:22:in `method_missing'

Am I missing anything?

Upvotes: 1

Views: 121

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

To further jbmyid's answer, you will benefit from looking at the difference between instance & class methods

What you're doing is trying to populate a new instance of the class using an instance method

This won't work, as instance methods are designed to load on a class which has already fired itsinitialize method. As your read_attr_from_file is not part of any predefined class, you'll need to make it a class method


Update

If you're trying to call a class method, it doesn't matter what the class is; you just have to do it without the class being initialized previously. I.E:

def self.read_attr_from_file filename
  ...
end

#-> User.read_attr_from_file filename

If you wanted to call a method on an already initialized class (an instance of a class), you'll be able to use:

def read_attr_from_file filename
end

# -> user = User.new
# -> user.read_attr_from_file

In terms of the answer, you have to remember that you're calling User.new (class method), but in order to populate the new object, you'll need to use another method, which will be run on a non-initialized object, hence it needs to be a class method:

Class User < ActiveRecord::Base

   def self.make_from_file filename
       User.new read_attr_from_file(filename)

       #-> User.new is class method
       #-> read_attr_from_file called on class, needs to be class method
   end

   private

   def self.read_attr_from_file filename
   end

end

Upvotes: 1

jbmyid
jbmyid

Reputation: 2015

class User

   def self.make_from_file(filename)
      User.new(read_attr_from_file(filename))
   end

   private

   def self.read_attr_from_file(filename)
      ...
   end

end

Try this

Upvotes: 3

Related Questions