ruby - Rails - Force model to be created via factory method -


I am using rail 4. I have a class, a car that has to be transported to within my app .

I want to access it using factory pattern:

  class CartFactory def self.obtain_cart_for_user (user) ... end end  

I want this approach because sometimes, I want to return to an existing car and sometimes a new construction (based on the cart, its content, whether it is still available on the basis of available products etc.) Want to do

It is quite easy.

However, I also want to make sure that any other future programmer does not directly direct the car, or through any other medium, organizations, such as:

  cart.new (...) user.carts.new (...) Cart.find (id) Cart.find_by_attribute (blah: blah) Cart.where (...) First  

Is there any way to prevent this from happening?

OK, this is possible:

  private_class_method: New < / Code> 

And of course, you are also ActiveRecord query method ( .panda , .where etc) But I think that seems like a good way to end up with irregular behavior if you want to go this route, make sure your app is fully tested first.


Another route will be for cart ActiveRecord :: Base (which I believe does that), and instead only Parts are required, such as ActiveRecord :: Perseverance if you are interested in diving deep, then see the parts involved in it.


Edit: An alternative cart must be made private within a module that only exposes CartFactory . There is no underlying syntax for any "private class", but again, do not know how well ActiveRecord will deal with that.


But in the end it is definitely the question that you want to do all this. In general, Ruby is not very good to protect you from yourself :) As explained in the subsequent linked reply, documentation and belief set a long way.


Comments

Popular posts from this blog

Member with no value in F# -

java - Joda Time Interval Not returning what I expect -

c# - Showing a SelectedItem's Property -