2

I am new to ROR and trying to convert my PhP application to ROR application. There is one php file common.php which is included in almost all other files. Likewise common.php in turn uses RPCClient.php and User.php . Variables and methods are shared across php files. So, what should I use in ROR a class or a module as data is shared among various files.

  • Possible duplicate of [What is the difference between include and require in Ruby?](https://stackoverflow.com/questions/318144/what-is-the-difference-between-include-and-require-in-ruby) – RiggsFolly May 09 '18 at 16:53
  • 1
    This is not a duplicate of the nominated exemplar, although that question does have some relevance, since the solution to the OP's problem will use "require" and "include." – Wayne Conrad May 09 '18 at 16:58

1 Answers1

4

In Ruby you'll want to organize things into namespaces, and the best way to do that is through class and module declarations.

Generally a class is something you'll make an instance of, and a module is something that's either "mixed in" (e.g. a set of methods imported by other modules or classes), or used directly.

For example:

class User < ActiveRecord::Base
end

Here Users is a class because you create users, and each user is represented by an object.

You can also declare methods as "mixins", or includable modules:

module UserPermissions
  def can_delete_post?(post)
    post.user_id == self.id
  end
end

class User < ActiveRecord::Base
  include UserPermissions
end

Where now user.can_delete_post? is a valid method and that method executes inside the context of a given user instance.

You can also make modules that are just collections of methods you can call directly:

module AppConfig
  def self.account_limit
    1
  end
end

AppConfig.account_limit
# => 1

Where you can call that method directly without having to include it. This is a fairly common pattern as well, it's just an organizational namespace.

Like many object-oriented languages, especially Smalltalk-derived ones, you'll want to read up on object oriented design patterns to see how to structure things properly.

tadman
  • 208,517
  • 23
  • 234
  • 262