35
loading...
This website collects cookies to deliver better user experience
class PostRepository
def find(id)
Post.find(id)
end
def all_published
Post.where(published: true).all
end
# ...
end
module LoudInteger
refine Integer do
def hello
"hello, #{self}!"
end
end
end
11.hello # => NoMethodError (undefined method `hello' for 11:Integer)
using LoudInteger
11.hello # => "hello, 11!"
You may activate refinements at top-level, and inside classes and modules. You may not activate refinements in method scope. Refinements are activated until the end of the current class or module definition, or until the end of the current file if used at the top-level.
DomainLayer
. The api I want is very simple - at the beginning of a file that encapsulates domain logic I will call my refinements. When there is persistence method called inside this file, I want it to raise exception. Like this:# frozen_string_literal: true
using DomainLayer
class PostService
def publish(id)
post = Post.find(id) # boom!
post.publish
post.save!
end
end
module DomainLayer
DomainLayerAccessError = Class.new(StandardError)
refine ActiveRecord::Base do
def find(*)
raise DomainLayerAccessError, "don't use persistence methods in domain layer!"
end
end
end
Failure/Error: raise DomainLayerAccessError, "don't use persistence methods in domain layer!"
DomainLayer::DomainLayerAccessError:
don't use persistence methods in domain layer!
# ./app/lib/domain_layer.rb:8:in `find'
# ./app/domains/cms/post_service.rb:7:in `publish'
# frozen_string_literal: true
using DomainLayer
class PostService
def initialize(post_repository: PostRepository.new)
@post_repository = post_repository
end
def publish(id)
post = post_repository.find(id)
post.publish
post_repository.save(post)
end
private
attr_reader :post_repository
end
Finished in 0.32838 seconds (files took 0.58 seconds to load)
1 example, 0 failures