ruby module structure insight

时间:2015-07-29 00:23:31

标签: ruby module packages

I'm new to Ruby and i'm making a Ruby package. structure is:

  def self.auto_assign_next(access_level)
    case 
    when access_level = 2 
      where("completed = 'f'").order("requested_time ASC").limit(1)
    when access_level > 2 
      where("completed = 'f'").order("CASE WHEN form='supervisor' THEN 1 WHEN form='installer' THEN 2 WHEN form='repair' THEN 3 WHEN form='mail' THEN 4 WHEN form='hp' THEN 5 ELSE 6 END").limit(1)
  end

If i put all the codes in my three modules file (discrete, randgen and simevent) in the ["Eventsims" module inside the eventsims.rb file], it is easy but there would be up to 1000 lines of code which I don't want

Now I have a "require" lines of code inside eventsim.rb that requires all these four files in the eventsim subfolder.

I can use all the modules, no errors. for example in the discrete.rb, a module called Discrete with a Calculate class having an expectval method:

Is this how I would be able to use the package after installing it with Rubygems

eventsims (main folder)
  |__lib
     |__eventsims {subfolder)
     |  |__discrete.rb
     |  |__randgen.rb
     |  |__simevent.rb
     |  |version.rb
     |__eventsims.rb

and if yes, is it sensible to have it that way because so many modules I've seen will have something like:

require "Eventsims"
a = Discrete::Calculate.new([1,0,4,2], [0.2, 0.4, 0.6, 1.0])
a.expectval()

which in my case would be require "eventsims" Discrete::someclass.new

I'm worried about the consistency of the required file and its namespacing. require eventsim and its different Discrete

Sorry the question is really long.

1 个答案:

答案 0 :(得分:0)

Unlike some other languages, Ruby does not tie the filesystem names to module hierarchy. If you want to have window.top.location.href = url provide the module require "eventsims", you can. Whether or not it's a good idea, it is for you to decide - Ruby is not your Mum. There are two potential pitfalls:

  • Gem users might get confused, and wonder how to use your gem
  • Someone in some other gem also defines Discrete and you have a collision.

A compromise between the two approaches (having a distinct namespace and having less to type) is to indeed have a top module Discrete, and for users to EventSims it if they want to access the next level down directly:

include

This way, you still have namespacing, and you can get rid of it when you know there is no collision in your code. Going the other way around (having no namespacing and trying to isolate the code when a collision does happen) is significantly more difficult.