Best practice for isolating data access level in Ruby / Rails

So I have a Ruby on Rails application. While empty. And let me tell you from the very beginning that most of my experience is with Java, so I can’t think about how RoR developers do. :-)

What I need to do is create some level of data access, let's say that they will be access users, so let it be UserDAO.rb, which will mainly use ActiveRecord or directly access the database or access or store data with the key or everything I can think of.

Technically, since we don’t have any interfaces in Ruby, I can get UserDAO.rb to “have” an implementation (basically I'm talking about composition), which can be anything, say, UserDAOActiveRecord.rb or UserDAOMongo.rb or something else like that. UserDAO.rb will basically call the implementation methods and what it is. It should be easy to switch between implementations.

While this sounds like a possible solution, I look forward to finding out what are the best practices for this issue in the Ruby world. Thank!

+3
source share
3 answers

You will need to look for a Ruby class other than ActiveRecord (which, as indicated, is an object-relational Mapper, therefore does not have a separate level of data access).

: http://sequel.rubyforge.org/

Person, , Sequel .

, :

class Person
  attr_reader :first_name, :last_name

  DataSource = Sequel.sqlite('my_app.db')[:people]

  def initialize(record)
    @first_name = record.first_name
    @last_name = record.last_name
  end

  # Find a record from the database and use it to initialize a new Person object 
  def self.find_by_id(id)
    self.new(Table.where(:id => id))
  end
end
+3

, ActiveRecord - , , : , // , , .

, , Rails, , ActiveRecord , , .

, ActiveRecord , MySQL, Oracle .. .

, , , . , Ruby Java-, , . , , , , ( ), , , . Java, , , . .

+2

Alex, I strongly suggest you get the book Agile Web Devoplment With Rails (4th Edition). Active Record implements ... an active recording template, so the class is a DAO (class methods represent dao), while instance methods represent an object.

So for example, you can have

person = Person.find(3)   //Person is the dao
person.name = 'mick'      //name = is the setter for he instance
person.save               // well.. saves the object

I coded in Java for 10 years and just started with ruby ​​..... and that has completely changed.

+1
source

Source: https://habr.com/ru/post/1793080/


All Articles