repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/slim.rb | middleman-core/lib/middleman-core/renderers/slim.rb | # Load gem
require 'slim'
module SafeTemplate
def render(*)
super.html_safe
end
end
class ::Slim::Template
include SafeTemplate
def initialize(file, line, opts, &block)
if opts.key?(:context)
::Slim::Embedded::SassEngine.disable_option_validator!
%w(sass scss markdown).each do |engine|
(::Slim::Embedded.options[engine.to_sym] ||= {})[:context] = opts[:context]
end
end
super
end
def precompiled_preamble(locals)
"__in_slim_template = true\n" << super
end
end
module Middleman
module Renderers
# Slim renderer
class Slim < ::Middleman::Extension
# Setup extension
def initialize(_app, _options={}, &_block)
super
# Setup Slim options to work with partials
::Slim::Engine.disable_option_validator!
::Slim::Engine.set_options(
buffer: '@_out_buf',
use_html_safe: true,
disable_escape: true
)
begin
require "action_view"
rescue LoadError
# Don't add generator option if action_view is not available, since it depends on it
else
::Slim::Engine.set_options(
generator: ::Temple::Generators::RailsOutputBuffer,
)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/dns_resolver/local_link_resolver.rb | middleman-core/lib/middleman-core/dns_resolver/local_link_resolver.rb | require 'middleman-core/dns_resolver/basic_network_resolver'
module Middleman
class DnsResolver
# Use network name server to resolve ips and names
class LocalLinkResolver < BasicNetworkResolver
def initialize(opts={})
super
@timeouts = opts.fetch(:timeouts, 1)
@resolver = opts.fetch(:resolver, Resolv::MDNS.new(nameserver_config))
self.timeouts = timeouts
end
private
# Hosts + Ports for MDNS resolver
#
# This looks for MM_MDNSRC in your environment. If you are going to use
# IPv6-addresses: Make sure you do not forget to add the port at the end.
#
# MM_MDNSRC=ip:port ip:port
#
# @return [Hash]
# Returns the configuration for the nameserver
#
# @example
# export MM_MDNSRC="224.0.0.251:5353 ff02::fb:5353"
#
def nameserver_config
return unless ENV.key?('MM_MDNSRC') && ENV['MM_MDNSRC']
address, port = ENV['MM_MDNSRC'].split(/:/)
{
nameserver_port: [[address, port.to_i]]
}
rescue StandardError
{}
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/dns_resolver/basic_network_resolver.rb | middleman-core/lib/middleman-core/dns_resolver/basic_network_resolver.rb | module Middleman
class DnsResolver
# Use network name server to resolve ips and names
class BasicNetworkResolver
private
attr_reader :resolver, :timeouts
public
def initialize(opts={})
@timeouts = opts.fetch(:timeouts, 2)
end
# Get names for ip
#
# @param [#to_s] ip
# The ip to resolve into names
#
# @return [Array]
# Array of Names
def getnames(ip)
resolver.getnames(ip.to_s).map(&:to_s)
rescue Resolv::ResolvError, Errno::EADDRNOTAVAIL
[]
end
# Get ips for name
#
# @param [#to_s] name
# The name to resolve into ips
#
# @return [Array]
# Array of ipaddresses
def getaddresses(name)
resolver.getaddresses(name.to_s).map(&:to_s)
rescue Resolv::ResolvError, Errno::EADDRNOTAVAIL
[]
end
# Set timeout for lookup
#
# @param [Integer] value
# The timeout value
def timeouts=(timeouts)
resolver.timeouts = timeouts
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/dns_resolver/network_resolver.rb | middleman-core/lib/middleman-core/dns_resolver/network_resolver.rb | require 'middleman-core/dns_resolver/basic_network_resolver'
module Middleman
class DnsResolver
# Use network name server to resolve ips and names
class NetworkResolver < BasicNetworkResolver
def initialize(opts={})
super
@resolver = opts.fetch(:resolver, Resolv::DNS.new(nameserver_config))
self.timeouts = timeouts
end
private
# Hosts + Ports for MDNS resolver
#
# This looks for MM_MDNSRC in your environment. If you are going to use
# IPv6-addresses: Make sure you do not forget to add the port at the end.
#
# MM_MDNSRC=ip:port ip:port
#
# @return [Hash]
# Returns the configuration for the nameserver
#
# @example
# export MM_MDNSRC="224.0.0.251:5353 ff02::fb:5353"
#
def nameserver_config
return unless ENV.key?('MM_DNSRC') && ENV['MM_DNSRC']
address, port = ENV['MM_DNSRC'].split(/:/)
{
nameserver_port: [[address, port.to_i]]
}
rescue StandardError
{}
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/dns_resolver/hosts_resolver.rb | middleman-core/lib/middleman-core/dns_resolver/hosts_resolver.rb | module Middleman
class DnsResolver
# Use network name server to resolve ips and names
class HostsResolver
private
attr_reader :resolver
public
def initialize(opts={})
# using the splat operator works around a non-existing HOSTSRC variable
# using nil as input does not work, but `*[]` does and then Resolv::Hosts
# uses its defaults
@resolver = opts.fetch(:resolver, Resolv::Hosts.new(*hosts_file))
end
# Get names for ip
#
# @param [#to_s] ip
# The ip to resolve into names
#
# @return [Array]
# Array of Names
def getnames(ip)
resolver.getnames(ip.to_s).map(&:to_s)
rescue Resolv::ResolvError
[]
end
# Get ips for name
#
# @param [#to_s] name
# The name to resolve into ips
#
# @return [Array]
# Array of ipaddresses
def getaddresses(name)
resolver.getaddresses(name.to_s).map(&:to_s)
rescue Resolv::ResolvError
[]
end
private
# Path to hosts file
#
# This looks for MM_HOSTSRC in your environment
#
# @return [Array]
# This needs to be an array, to make the splat operator work
#
# @example
# # <ip> <hostname>
# 127.0.0.1 localhost.localhost localhost
def hosts_file
return [ENV['MM_HOSTSRC']] if ENV.key?('MM_HOSTSRC') && File.file?(ENV['MM_HOSTSRC'])
[]
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/resource.rb | middleman-core/lib/middleman-core/sitemap/resource.rb | require 'rack/mime'
require 'middleman-core/sitemap/extensions/traversal'
require 'middleman-core/file_renderer'
require 'middleman-core/template_renderer'
require 'middleman-core/contracts'
module Middleman
# Sitemap namespace
module Sitemap
# Sitemap Resource class
class Resource
include Contracts
include Middleman::Sitemap::Extensions::Traversal
# The source path of this resource (relative to the source directory,
# without template extensions)
# @return [String]
attr_reader :path
# The output path in the build directory for this resource
# @return [String]
attr_accessor :destination_path
# The on-disk source file for this resource, if there is one
# @return [String]
Contract Maybe[IsA['Middleman::SourceFile']]
attr_reader :file_descriptor
# The path to use when requesting this resource. Normally it's
# the same as {#destination_path} but it can be overridden in subclasses.
# @return [String]
alias request_path destination_path
METADATA_HASH = { options: Maybe[Hash], locals: Maybe[Hash], page: Maybe[Hash] }.freeze
# The metadata for this resource
# @return [Hash]
Contract METADATA_HASH
attr_reader :metadata
attr_accessor :ignored
# Initialize resource with parent store and URL
# @param [Middleman::Sitemap::Store] store
# @param [String] path
# @param [String] source
Contract IsA['Middleman::Sitemap::Store'], String, Maybe[Or[IsA['Middleman::SourceFile'], String]] => Any
def initialize(store, path, source=nil)
@store = store
@app = @store.app
@path = path
@ignored = false
source = Pathname(source) if source && source.is_a?(String)
@file_descriptor = if source && source.is_a?(Pathname)
::Middleman::SourceFile.new(source.relative_path_from(@app.source_dir), source, @app.source_dir, Set.new([:source]), 0)
else
source
end
@destination_path = @path
# Options are generally rendering/sitemap options
# Locals are local variables for rendering this resource's template
# Page are data that is exposed through this resource's data member.
# Note: It is named 'page' for backwards compatibility with older MM.
@metadata = { options: {}, locals: {}, page: {} }
@page_data = nil
end
# Whether this resource has a template file
# @return [Boolean]
Contract Bool
def template?
return false if file_descriptor.nil?
!::Middleman::Util.tilt_class(file_descriptor[:full_path].to_s).nil?
end
# Backwards compatible method for turning descriptor into a string.
# @return [String]
Contract Maybe[String]
def source_file
file_descriptor && file_descriptor[:full_path].to_s
end
Contract Or[Symbol, String, Integer]
def page_id
metadata[:page][:id] || make_implicit_page_id(destination_path)
end
# Merge in new metadata specific to this resource.
# @param [Hash] meta A metadata block with keys :options, :locals, :page.
# Options are generally rendering/sitemap options
# Locals are local variables for rendering this resource's template
# Page are data that is exposed through this resource's data member.
# Note: It is named 'page' for backwards compatibility with older MM.
Contract METADATA_HASH, Maybe[Bool] => METADATA_HASH
def add_metadata(meta={}, reverse=false)
@page_data = nil
@metadata = if reverse
meta.deep_merge(@metadata)
else
@metadata.deep_merge(meta)
end
end
# Data about this resource, populated from frontmatter or extensions.
# @return [Hash]
Contract RespondTo[:indifferent_access?]
def data
@page_data ||= ::Middleman::Util.recursively_enhance(metadata[:page])
end
# Options about how this resource is rendered, such as its :layout,
# :renderer_options, and whether or not to use :directory_indexes.
# @return [Hash]
Contract Hash
def options
metadata[:options]
end
# Local variable mappings that are used when rendering the template for this resource.
# @return [Hash]
Contract Hash
def locals
metadata[:locals]
end
# Extension of the path (i.e. '.js')
# @return [String]
Contract String
def ext
File.extname(path)
end
# Render this resource
# @return [String]
Contract Hash, Hash => String
def render(opts={}, locs={})
return ::Middleman::FileRenderer.new(@app, file_descriptor[:full_path].to_s).template_data_for_file unless template?
md = metadata
opts = md[:options].deep_merge(opts)
locs = md[:locals].deep_merge(locs)
locs[:current_path] ||= destination_path
# Certain output file types don't use layouts
opts[:layout] = false if !opts.key?(:layout) && !@app.config.extensions_with_layout.include?(ext)
renderer = ::Middleman::TemplateRenderer.new(@app, file_descriptor[:full_path].to_s)
renderer.render(locs, opts)
end
# A path without the directory index - so foo/index.html becomes
# just foo. Best for linking.
# @return [String]
Contract String
def url
url_path = destination_path
if @app.config[:strip_index_file]
url_path = url_path.sub(/(^|\/)#{Regexp.escape(@app.config[:index_file])}$/,
@app.config[:trailing_slash] ? '/' : '')
end
File.join(@app.config[:http_prefix], url_path)
end
# Whether the source file is binary.
#
# @return [Boolean]
Contract Bool
def binary?
!file_descriptor.nil? && (file_descriptor[:types].include?(:binary) || ::Middleman::Util.binary?(file_descriptor[:full_path].to_s))
end
# Ignore a resource directly, without going through the whole
# ignore filter stuff.
# @return [void]
Contract Any
def ignore!
@ignored = true
end
# Whether the Resource is ignored
# @return [Boolean]
Contract Bool
def ignored?
@ignored
end
# The preferred MIME content type for this resource based on extension or metadata
# @return [String] MIME type for this resource
Contract Maybe[String]
def content_type
options[:content_type] || ::Rack::Mime.mime_type(ext, nil)
end
# The normalized source path of this resource (relative to the source directory,
# without template extensions)
# @return [String]
def normalized_path
@normalized_path ||= ::Middleman::Util.normalize_path @path
end
def to_s
"#<#{self.class} path=#{@path}>"
end
alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
protected
# Makes a page id based on path (when not otherwise given)
#
# Removes .html extension and potential leading slashes or dots
# eg. "foo/bar/baz.foo.html" => "foo/bar/baz.foo"
Contract String => String
def make_implicit_page_id(path)
@id ||= begin
if prok = @app.config[:page_id_generator]
return prok.call(path)
end
basename = if ext == '.html'
File.basename(path, ext)
else
File.basename(path)
end
# Remove leading dot or slash if present
File.join(File.dirname(path), basename).gsub(/^\.?\//, '')
end
end
end
class StringResource < Resource
def initialize(store, path, contents=nil, &block)
@request_path = path
@contents = block_given? ? block : contents
super(store, path)
end
def template?
true
end
def render(*)
@contents.respond_to?(:call) ? @contents.call : @contents
end
def binary?
false
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/store.rb | middleman-core/lib/middleman-core/sitemap/store.rb | # Used for merging results of metadata callbacks
require 'active_support/core_ext/hash/deep_merge'
require 'monitor'
require 'hamster'
require 'middleman-core/extensions'
# Files on Disk
::Middleman::Extensions.register :sitemap_ondisk, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/on_disk'
::Middleman::Sitemap::Extensions::OnDisk
end
# Files on Disk (outside the project root)
::Middleman::Extensions.register :sitemap_import, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/import'
::Middleman::Sitemap::Extensions::Import
end
# Endpoints
::Middleman::Extensions.register :sitemap_endpoint, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/request_endpoints'
::Middleman::Sitemap::Extensions::RequestEndpoints
end
# Proxies
::Middleman::Extensions.register :sitemap_proxies, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/proxies'
::Middleman::Sitemap::Extensions::Proxies
end
# Redirects
::Middleman::Extensions.register :sitemap_redirects, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/redirects'
::Middleman::Sitemap::Extensions::Redirects
end
# Move Files
::Middleman::Extensions.register :sitemap_move_files, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/move_file'
::Middleman::Sitemap::Extensions::MoveFile
end
# Ignores
::Middleman::Extensions.register :sitemap_ignore, auto_activate: :before_configuration do
require 'middleman-core/sitemap/extensions/ignores'
::Middleman::Sitemap::Extensions::Ignores
end
require 'middleman-core/contracts'
module Middleman
# Sitemap namespace
module Sitemap
ManipulatorDescriptor = Struct.new :name, :manipulator, :priority, :custom_name
# The Store class
#
# The Store manages a collection of Resource objects, which represent
# individual items in the sitemap. Resources are indexed by "source path",
# which is the path relative to the source directory, minus any template
# extensions. All "path" parameters used in this class are source paths.
class Store
include Contracts
Contract IsA['Middleman::Application']
attr_reader :app
Contract Num
attr_reader :update_count
# Initialize with parent app
# @param [Middleman::Application] app
Contract IsA['Middleman::Application'] => Any
def initialize(app)
@app = app
@resources = []
@rebuild_reasons = [:first_run]
@update_count = 0
@resource_list_manipulators = ::Hamster::Vector.empty
@needs_sitemap_rebuild = true
@lock = Monitor.new
reset_lookup_cache!
@app.config_context.class.send :def_delegator, :app, :sitemap
end
Contract Symbol, RespondTo[:manipulate_resource_list], Maybe[Or[Num, ArrayOf[Num]]], Maybe[Symbol] => Any
def register_resource_list_manipulators(name, manipulator, priority=50, custom_name=nil)
Array(priority || 50).each do |p|
register_resource_list_manipulator(name, manipulator, p, custom_name)
end
end
# Register an object which can transform the sitemap resource list. Best to register
# these in a `before_configuration` or `after_configuration` hook.
#
# @param [Symbol] name Name of the manipulator for debugging
# @param [#manipulate_resource_list] manipulator Resource list manipulator
# @param [Numeric] priority Sets the order of this resource list manipulator relative to the rest. By default this is 50, and manipulators run in the order they are registered, but if a priority is provided then this will run ahead of or behind other manipulators.
# @param [Symbol] custom_name The method name to execute.
# @return [void]
Contract Symbol, RespondTo[:manipulate_resource_list], Maybe[Num, Bool], Maybe[Symbol] => Any
def register_resource_list_manipulator(name, manipulator, priority=50, custom_name=nil)
# The third argument used to be a boolean - handle those who still pass one
priority = 50 unless priority.is_a? Numeric
@resource_list_manipulators = @resource_list_manipulators.push(
ManipulatorDescriptor.new(name, manipulator, priority, custom_name)
)
# The index trick is used so that the sort is stable - manipulators with the same priority
# will always be ordered in the same order as they were registered.
n = 0
@resource_list_manipulators = @resource_list_manipulators.sort_by do |m|
n += 1
[m[:priority], n]
end
rebuild_resource_list!(:"registered_new_manipulator_#{name}")
end
# Rebuild the list of resources from scratch, using registed manipulators
# @return [void]
Contract Symbol => Any
def rebuild_resource_list!(name)
@lock.synchronize do
@rebuild_reasons << name
@app.logger.debug "== Requesting resource list rebuilding: #{name}"
@needs_sitemap_rebuild = true
end
end
# Find a resource given its original path
# @param [String] request_path The original path of a resource.
# @return [Middleman::Sitemap::Resource]
Contract String => Maybe[IsA['Middleman::Sitemap::Resource']]
def find_resource_by_path(request_path)
@lock.synchronize do
request_path = ::Middleman::Util.normalize_path(request_path)
ensure_resource_list_updated!
@_lookup_by_path[request_path]
end
end
# Find a resource given its destination path
# @param [String] request_path The destination (output) path of a resource.
# @return [Middleman::Sitemap::Resource]
Contract String => Maybe[IsA['Middleman::Sitemap::Resource']]
def find_resource_by_destination_path(request_path)
@lock.synchronize do
request_path = ::Middleman::Util.normalize_path(request_path)
ensure_resource_list_updated!
@_lookup_by_destination_path[request_path]
end
end
# Find a resource given its page id
# @param [String] page_id The page id.
# @return [Middleman::Sitemap::Resource]
Contract Or[String, Symbol] => Maybe[IsA['Middleman::Sitemap::Resource']]
def find_resource_by_page_id(page_id)
@lock.synchronize do
ensure_resource_list_updated!
@_lookup_by_page_id[page_id.to_s.to_sym]
end
end
# Get the array of all resources
# @param [Boolean] include_ignored Whether to include ignored resources
# @return [Array<Middleman::Sitemap::Resource>]
Contract Bool => ResourceList
def resources(include_ignored=false)
@lock.synchronize do
ensure_resource_list_updated!
if include_ignored
@resources
else
@resources_not_ignored ||= @resources.reject(&:ignored?)
end
end
end
# Invalidate our cached view of resource that are not ignored. If your extension
# adds ways to ignore files, you should call this to make sure #resources works right.
def invalidate_resources_not_ignored_cache!
@resources_not_ignored = nil
end
# Get the URL path for an on-disk file
# @param [String] file
# @return [String]
Contract Or[Pathname, IsA['Middleman::SourceFile']] => String
def file_to_path(file)
relative_path = file.is_a?(Pathname) ? file.to_s : file[:relative_path].to_s
# Replace a file name containing automatic_directory_matcher with a folder
unless @app.config[:automatic_directory_matcher].nil?
relative_path = relative_path.gsub(@app.config[:automatic_directory_matcher], '/')
end
extensionless_path(relative_path)
end
# Get a path without templating extensions
# @param [String] file
# @return [String]
Contract String => String
def extensionless_path(file)
path = file.dup
::Middleman::Util.remove_templating_extensions(path)
end
# Actually update the resource list, assuming anything has called
# rebuild_resource_list! since the last time it was run. This is
# very expensive!
def ensure_resource_list_updated!
return if @app.config[:disable_sitemap]
@lock.synchronize do
return unless @needs_sitemap_rebuild
::Middleman::Util.instrument 'sitemap.update', reasons: @rebuild_reasons.uniq do
@needs_sitemap_rebuild = false
@app.logger.debug '== Rebuilding resource list'
@resources = []
@resource_list_manipulators.each do |m|
::Middleman::Util.instrument 'sitemap.manipulator', name: m[:name] do
@app.logger.debug "== Running manipulator: #{m[:name]} (#{m[:priority]})"
@resources = m[:manipulator].send(m[:custom_name] || :manipulate_resource_list, @resources)
# Reset lookup cache
reset_lookup_cache!
# Rebuild cache
@resources.each do |resource|
@_lookup_by_path[resource.path] = resource
end
@resources.each do |resource|
@_lookup_by_destination_path[resource.destination_path] = resource
end
# NB: This needs to be done after the previous two steps,
# since some proxy resources are looked up by path in order to
# get their metadata and subsequently their page_id.
@resources.each do |resource|
@_lookup_by_page_id[resource.page_id.to_s.to_sym] = resource
end
invalidate_resources_not_ignored_cache!
end
end
@update_count += 1
@rebuild_reasons = []
end
end
end
private
def reset_lookup_cache!
@lock.synchronize do
@_lookup_by_path = {}
@_lookup_by_destination_path = {}
@_lookup_by_page_id = {}
end
end
# Remove the locale token from the end of the path
# @param [String] path
# @return [String]
Contract String => String
def strip_away_locale(path)
if @app.extensions[:i18n]
path_bits = path.split('.')
lang = path_bits.last
return path_bits[0..-2].join('.') if @app.extensions[:i18n].langs.include?(lang.to_sym)
end
path
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/redirects.rb | middleman-core/lib/middleman-core/sitemap/extensions/redirects.rb | require 'middleman-core/sitemap/resource'
require 'middleman-core/contracts'
module Middleman
module Sitemap
module Extensions
# Manages the list of proxy configurations and manipulates the sitemap
# to include new resources based on those configurations
class Redirects < ConfigExtension
self.resource_list_manipulator_priority = 0
# Expose `redirect`
expose_to_config :redirect
RedirectDescriptor = Struct.new(:path, :to, :template) do
def execute_descriptor(app, resources)
r = RedirectResource.new(
app.sitemap,
path,
to
)
r.output = template if template
resources + [r]
end
end
# Setup a redirect from a path to a target
# @param [String] path
# @param [Hash] opts The :to value gives a target path
Contract String, { to: Or[String, ::Middleman::Sitemap::Resource] }, Maybe[Proc] => RedirectDescriptor
def redirect(path, opts={}, &block)
RedirectDescriptor.new(path, opts[:to], block_given? ? block : nil)
end
end
class RedirectResource < ::Middleman::Sitemap::Resource
Contract Maybe[Proc]
attr_accessor :output
def initialize(store, path, target)
@request_path = target
super(store, path)
end
Contract Bool
def template?
true
end
Contract Args[Any] => String
def render(*)
url = ::Middleman::Util.url_for(@store.app, @request_path,
relative: false,
find_resource: true)
if output
output.call(path, url)
else
<<-END
<html>
<head>
<link rel="canonical" href="#{url}" />
<meta http-equiv=refresh content="0; url=#{url}" />
<meta name="robots" content="noindex,follow" />
<meta http-equiv="cache-control" content="no-cache" />
</head>
<body>
</body>
</html>
END
end
end
Contract Bool
def ignored?
false
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/proxies.rb | middleman-core/lib/middleman-core/sitemap/extensions/proxies.rb | require 'middleman-core/sitemap/resource'
require 'middleman-core/core_extensions/collections/step_context'
module Middleman
module Sitemap
module Extensions
# Manages the list of proxy configurations and manipulates the sitemap
# to include new resources based on those configurations
class Proxies < ConfigExtension
self.resource_list_manipulator_priority = 0
# Expose `proxy`
expose_to_config :proxy
# Setup a proxy from a path to a target
# @param [String] path The new, proxied path to create
# @param [String] target The existing path that should be proxied to. This must be a real resource, not another proxy.
# @option opts [Boolean] ignore Ignore the target from the sitemap (so only the new, proxy resource ends up in the output)
# @option opts [Symbol, Boolean, String] layout The layout name to use (e.g. `:article`) or `false` to disable layout.
# @option opts [Boolean] directory_indexes Whether or not the `:directory_indexes` extension applies to these paths.
# @option opts [Hash] locals Local variables for the template. These will be available when the template renders.
# @option opts [Hash] data Extra metadata to add to the page. This is the same as frontmatter, though frontmatter will take precedence over metadata defined here. Available via {Resource#data}.
# @return [ProxyDescriptor]
Contract String, String, Maybe[Hash] => RespondTo[:execute_descriptor]
def proxy(path, target, opts={})
ProxyDescriptor.new(
::Middleman::Util.normalize_path(path),
::Middleman::Util.normalize_path(target),
opts.dup
)
end
end
ProxyDescriptor = Struct.new(:path, :target, :metadata) do
def execute_descriptor(app, resources)
md = metadata.dup
should_ignore = md.delete(:ignore)
page_data = md.delete(:data) || {}
page_data[:id] = md.delete(:id) if md.key?(:id)
r = ProxyResource.new(app.sitemap, path, target)
r.add_metadata(
locals: md.delete(:locals) || {},
page: page_data || {},
options: md
)
if should_ignore
d = ::Middleman::Sitemap::Extensions::Ignores::StringIgnoreDescriptor.new(target)
d.execute_descriptor(app, resources)
end
resources + [r]
end
end
end
class Resource
def proxy_to(_path)
throw 'Resource#proxy_to has been removed. Use ProxyResource class instead.'
end
end
class ProxyResource < ::Middleman::Sitemap::Resource
Contract String
attr_reader :target
# Initialize resource with parent store and URL
# @param [Middleman::Sitemap::Store] store
# @param [String] path
# @param [String] target
def initialize(store, path, target)
super(store, path)
target = ::Middleman::Util.normalize_path(target)
raise "You can't proxy #{path} to itself!" if target == path
@target = target
end
# The resource for the page this page is proxied to. Throws an exception
# if there is no resource.
# @return [Sitemap::Resource]
Contract IsA['Middleman::Sitemap::Resource']
def target_resource
resource = @store.find_resource_by_path(@target)
unless resource
raise "Path #{path} proxies to unknown file #{@target}:#{@store.resources.map(&:path)}"
end
if resource.is_a? ProxyResource
raise "You can't proxy #{path} to #{@target} which is itself a proxy."
end
resource
end
Contract IsA['Middleman::SourceFile']
def file_descriptor
target_resource.file_descriptor
end
def metadata
target_resource.metadata.deep_merge super
end
Contract Maybe[String]
def content_type
mime_type = super
return mime_type if mime_type
target_resource.content_type
end
def to_s
"#<#{self.class} path=#{@path} target=#{@target}>"
end
alias inspect to_s
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/on_disk.rb | middleman-core/lib/middleman-core/sitemap/extensions/on_disk.rb | require 'set'
require 'middleman-core/contracts'
module Middleman
module Sitemap
module Extensions
class OnDisk < Extension
self.resource_list_manipulator_priority = 0
def initialize(app, config={}, &block)
super
@file_paths_on_disk = Set.new
@waiting_for_ready = true
end
def ready
@waiting_for_ready = false
# Make sure the sitemap is ready for the first request
app.sitemap.ensure_resource_list_updated!
end
Contract Any
def before_configuration
app.files.on_change(:source, &method(:update_files))
end
Contract IsA['Middleman::SourceFile'] => Bool
def ignored?(file)
@app.config[:ignored_sitemap_matchers].any? do |_, callback|
callback.call(file, @app)
end
end
# Update or add an on-disk file path
# @param [String] file
# @return [void]
Contract ArrayOf[IsA['Middleman::SourceFile']], ArrayOf[IsA['Middleman::SourceFile']] => Any
def update_files(updated_files, removed_files)
return if (updated_files + removed_files).all?(&method(:ignored?))
# Rebuild the sitemap any time a file is touched
# in case one of the other manipulators
# (like asset_hash) cares about the contents of this file,
# whether or not it belongs in the sitemap (like a partial)
@app.sitemap.rebuild_resource_list!(:touched_file)
# Force sitemap rebuild so the next request is ready to go.
# Skip this during build because the builder will control sitemap refresh.
@app.sitemap.ensure_resource_list_updated! unless @waiting_for_ready || @app.build?
end
Contract ArrayOf[IsA['Middleman::SourceFile']]
def files_for_sitemap
@app.files.by_type(:source).files.reject(&method(:ignored?))
end
# Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
resources + files_for_sitemap.map do |file|
::Middleman::Sitemap::Resource.new(
@app.sitemap,
@app.sitemap.file_to_path(file),
file
)
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/move_file.rb | middleman-core/lib/middleman-core/sitemap/extensions/move_file.rb | require 'middleman-core/sitemap/resource'
require 'middleman-core/core_extensions/collections/step_context'
module Middleman
module Sitemap
module Extensions
# Manages the list of proxy configurations and manipulates the sitemap
# to include new resources based on those configurations
class MoveFile < ConfigExtension
self.resource_list_manipulator_priority = 101
# Expose `move_file`
expose_to_config :move_file
MoveFileDescriptor = Struct.new(:from, :to) do
def execute_descriptor(_app, resources)
resources.each do |r|
r.destination_path = to if from == r.path || from == r.destination_path
end
resources
end
end
# Setup a move from one path to another
# @param [String] from The original path.
# @param [String] to The new path.
# @return [void]
Contract String, String => MoveFileDescriptor
def move_file(from, to)
MoveFileDescriptor.new(
::Middleman::Util.normalize_path(from),
::Middleman::Util.normalize_path(to)
)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/request_endpoints.rb | middleman-core/lib/middleman-core/sitemap/extensions/request_endpoints.rb | require 'middleman-core/sitemap/resource'
module Middleman
module Sitemap
module Extensions
class RequestEndpoints < ConfigExtension
self.resource_list_manipulator_priority = 0
# Expose `endpoint`
expose_to_config :endpoint
EndpointDescriptor = Struct.new(:path, :request_path, :block) do
def execute_descriptor(app, resources)
r = EndpointResource.new(
app.sitemap,
path,
request_path
)
r.output = block if block
resources + [r]
end
end
# Setup a proxy from a path to a target
# @param [String] path
# @param [Hash] opts The :path value gives a request path if it
# differs from the output path
Contract String, Or[{ path: String }, Proc] => EndpointDescriptor
def endpoint(path, opts={}, &block)
if block_given?
EndpointDescriptor.new(path, path, block)
else
EndpointDescriptor.new(path, opts[:path] || path, nil)
end
end
end
class EndpointResource < ::Middleman::Sitemap::Resource
Contract Maybe[Proc]
attr_accessor :output
def initialize(store, path, request_path)
super(store, path)
@request_path = ::Middleman::Util.normalize_path(request_path)
end
Contract String
attr_reader :request_path
Contract Bool
def template?
true
end
Contract Args[Any] => String
def render(*)
return output.call if output
end
Contract Bool
def ignored?
false
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/import.rb | middleman-core/lib/middleman-core/sitemap/extensions/import.rb | require 'set'
require 'middleman-core/contracts'
module Middleman
module Sitemap
module Extensions
class Import < ConfigExtension
self.resource_list_manipulator_priority = 1
# Expose methods
expose_to_config :import_file, :import_path
ImportFileDescriptor = Struct.new(:from, :to) do
def execute_descriptor(app, resources)
source = ::Middleman::SourceFile.new(Pathname(from).relative_path_from(app.source_dir), Pathname(from), app.source_dir, Set.new([:source, :binary]), 0)
resources + [
::Middleman::Sitemap::Resource.new(app.sitemap, to, source)
]
end
end
ImportPathDescriptor = Struct.new(:from, :renameProc) do
def execute_descriptor(app, resources)
resources + ::Middleman::Util.glob_directory(File.join(from, '**/*'))
.reject { |path| File.directory?(path) }
.map do |path|
target_path = Pathname(path).relative_path_from(Pathname(from).parent).to_s
::Middleman::Sitemap::Resource.new(
app.sitemap,
renameProc.call(target_path, path),
path
)
end
end
end
# Import an external file into `source`
# @param [String] from The original path.
# @param [String] to The new path.
# @return [void]
Contract String, String => ImportFileDescriptor
def import_file(from, to)
ImportFileDescriptor.new(
File.expand_path(from, @app.root),
::Middleman::Util.normalize_path(to)
)
end
# Import an external glob into `source`
# @param [String] from The original path.
# @param [Proc] block Renaming method
# @return [void]
Contract String, Maybe[Proc] => ImportPathDescriptor
def import_path(from, &block)
ImportPathDescriptor.new(
from,
block_given? ? block : proc { |path| path }
)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/ignores.rb | middleman-core/lib/middleman-core/sitemap/extensions/ignores.rb | module Middleman
module Sitemap
module Extensions
# Class to handle managing ignores
class Ignores < ConfigExtension
self.resource_list_manipulator_priority = 0
expose_to_application :ignore
expose_to_config :ignore
# Ignore a path or add an ignore callback
# @param [String, Regexp] path Path glob expression, or path regex
# @return [IgnoreDescriptor]
Contract Or[String, Regexp, Proc] => RespondTo[:execute_descriptor]
def ignore(path=nil, &block)
@app.sitemap.invalidate_resources_not_ignored_cache!
if path.is_a? Regexp
RegexpIgnoreDescriptor.new(path)
elsif path.is_a? String
path_clean = ::Middleman::Util.normalize_path(path)
if path_clean.include?('*') # It's a glob
GlobIgnoreDescriptor.new(path_clean)
else
StringIgnoreDescriptor.new(path_clean)
end
elsif block
BlockIgnoreDescriptor.new(nil, block)
else
IgnoreDescriptor.new(path, block)
end
end
IgnoreDescriptor = Struct.new(:path, :block) do
def execute_descriptor(_app, resources)
resources.map do |r|
# Ignore based on the source path (without template extensions)
if ignored?(r.normalized_path)
r.ignore!
elsif !r.is_a?(ProxyResource) && r.file_descriptor && ignored?(r.file_descriptor.normalized_relative_path)
# This allows files to be ignored by their source file name (with template extensions)
r.ignore!
end
r
end
end
def ignored?(_match_path)
raise NotImplementedError
end
end
class RegexpIgnoreDescriptor < IgnoreDescriptor
def ignored?(match_path)
match_path =~ path
end
end
class GlobIgnoreDescriptor < IgnoreDescriptor
def ignored?(match_path)
if defined?(::File::FNM_EXTGLOB)
::File.fnmatch(path, match_path, ::File::FNM_EXTGLOB)
else
::File.fnmatch(path, match_path)
end
end
end
class StringIgnoreDescriptor < IgnoreDescriptor
def ignored?(match_path)
match_path == path
end
end
class BlockIgnoreDescriptor < IgnoreDescriptor
def ignored?(match_path)
block.call(match_path)
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sitemap/extensions/traversal.rb | middleman-core/lib/middleman-core/sitemap/extensions/traversal.rb | module Middleman
module Sitemap
module Extensions
module Traversal
def traversal_root
root = if !@app.extensions[:i18n]
'/'
else
@app.extensions[:i18n].path_root(::I18n.locale)
end
root.sub(/^\//, '')
end
# This resource's parent resource
# @return [Middleman::Sitemap::Resource, nil]
def parent
root = path.sub(/^#{::Regexp.escape(traversal_root)}/, '')
parts = root.split('/')
tail = parts.pop
is_index = (tail == @app.config[:index_file])
if parts.empty?
return is_index ? nil : @store.find_resource_by_path(@app.config[:index_file])
end
test_expr = parts.join('\\/')
test_expr = %r{^#{test_expr}(?:\.[a-zA-Z0-9]+|\/)$}
# eponymous reverse-lookup
found = @store.resources.find do |candidate|
candidate.path =~ test_expr
end
if found
found
else
parts.pop if is_index
@store.find_resource_by_destination_path("#{parts.join('/')}/#{@app.config[:index_file]}")
end
end
# This resource's child resources
# @return [Array<Middleman::Sitemap::Resource>]
def children
return [] unless directory_index?
base_path = if eponymous_directory?
eponymous_directory_path
else
path.sub(@app.config[:index_file].to_s, '')
end
prefix = %r{^#{base_path.sub("/", "\\/")}}
@store.resources.select do |sub_resource|
if sub_resource.path == path || sub_resource.path !~ prefix
false
else
inner_path = sub_resource.path.sub(prefix, '')
parts = inner_path.split('/')
if parts.length == 1
true
elsif parts.length == 2
parts.last == @app.config[:index_file]
else
false
end
end
end
end
# This resource's sibling resources
# @return [Array<Middleman::Sitemap::Resource>]
def siblings
return [] unless parent
parent.children.reject { |p| p == self }
end
# Whether this resource is either a directory index, or has the same name as an existing directory in the source
# @return [Boolean]
def directory_index?
path.include?(@app.config[:index_file]) || path =~ /\/$/ || eponymous_directory?
end
# Whether the resource has the same name as a directory in the source
# (e.g., if the resource is named 'gallery.html' and a path exists named 'gallery/', this would return true)
# @return [Boolean]
def eponymous_directory?
if !path.end_with?("/#{@app.config[:index_file]}") && destination_path.end_with?("/#{@app.config[:index_file]}")
return true
end
@app.files.by_type(:source).watchers.any? do |source|
(source.directory + Pathname(eponymous_directory_path)).directory?
end
end
# The path for this resource if it were a directory, and not a file
# (e.g., for 'gallery.html' this would return 'gallery/')
# @return [String]
def eponymous_directory_path
path.sub(ext, '/').sub(/\/$/, '') + '/'
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/server_ip_address.rb | middleman-core/lib/middleman-core/preview_server/server_ip_address.rb | require 'ipaddr'
require 'forwardable'
module Middleman
class PreviewServer
class ServerIpAddress
def self.new(ip_address)
@parser = []
@parser << ServerIpv6Address
@parser << ServerIpv4Address
@parser.find { |p| p.match? ip_address }.new(ip_address)
end
end
class BasicServerIpAddress < SimpleDelegator
end
class ServerIpv4Address < BasicServerIpAddress
def to_browser
__getobj__.to_s
end
def self.match?(*)
true
end
end
class ServerIpv6Address < BasicServerIpAddress
def to_s
__getobj__.sub(/%.*$/, '')
end
def to_browser
format('[%s]', to_s)
end
def self.match?(str)
str = str.to_s.sub(/%.*$/, '')
IPAddr.new(str).ipv6?
rescue IPAddr::InvalidAddressError, IPAddr::AddressFamilyError
false
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/information.rb | middleman-core/lib/middleman-core/preview_server/information.rb | require 'ipaddr'
require 'active_support/core_ext/object/blank'
require 'middleman-core/preview_server/checks'
require 'middleman-core/preview_server/server_hostname'
require 'middleman-core/preview_server/server_ip_address'
module Middleman
class PreviewServer
# Basic information class to wrap common behaviour
class BasicInformation
private
attr_reader :checks, :network_interfaces_inventory
public
attr_accessor :bind_address, :server_name, :port, :reason, :valid
attr_reader :listeners, :site_addresses
# Create instance
#
# @param [String] bind_address
# The bind address of the server
#
# @param [String] server_name
# The name of the server
#
# @param [Integer] port
# The port to listen on
def initialize(opts={})
@bind_address = ServerIpAddress.new(opts[:bind_address])
@server_name = ServerHostname.new(opts[:server_name])
@port = opts[:port]
@valid = true
@site_addresses = []
@listeners = []
@checks = []
# This needs to be check for each use case. Otherwise `Webrick` will
# complain about that.
@checks << Checks::InterfaceIsAvailableOnSystem.new
end
# Is the given information valid?
def valid?
valid == true
end
# Pass "self" to validator
#
# @param [#validate] validator
# The validator
def validate_me(validator)
validator.validate self, checks
end
def resolve_me(*)
fail NoMethodError
end
# Get network information
#
# @param [#network_interfaces] inventory
# Get list of available network interfaces
def show_me_network_interfaces(inventory)
@network_interfaces_inventory = inventory
end
# Default is to get all network interfaces
def local_network_interfaces
network_interfaces_inventory.nil? ? [] : network_interfaces_inventory.network_interfaces(:all)
end
end
# This only is used if no other parser is available
#
# The "default" behaviour is to fail because of "Checks::DenyAnyAny"
class DefaultInformation < BasicInformation
def initialize(*args)
super
# Make this fail
@checks << Checks::DenyAnyAny.new
end
def resolve_me(*); end
# Always true
def self.matches?(*)
true
end
end
# This one is used if no bind address and no server name is given
class AllInterfaces < BasicInformation
def initialize(*args)
super
after_init
end
def self.matches?(opts={})
opts[:bind_address].blank? && opts[:server_name].blank?
end
# Resolve ips
def resolve_me(resolver)
hostname = ServerHostname.new(Socket.gethostname)
hostname_ips = resolver.ips_for(hostname)
network_interface = ServerIpAddress.new(Array(local_network_interfaces).first)
resolved_name = ServerHostname.new(resolver.names_for(network_interface).first)
if includes_array? local_network_interfaces, hostname_ips
@server_name = hostname
@site_addresses << hostname
network_interface = ServerIpAddress.new((local_network_interfaces & hostname_ips).first)
elsif RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/
@server_name = hostname
@site_addresses << hostname
elsif !resolved_name.blank?
@server_name = resolved_name
@site_addresses << resolved_name
else
@server_name = network_interface
end
@site_addresses << network_interface
self
end
private
def includes_array?(a, b)
!(a & b).empty?
end
def after_init
@listeners << ServerIpAddress.new('::')
@listeners << ServerIpAddress.new('0.0.0.0')
end
end
# This is used if bind address is 0.0.0.0, the server name needs to be
# blank
class AllIpv4Interfaces < AllInterfaces
def self.matches?(opts={})
opts[:bind_address] == '0.0.0.0' && opts[:server_name].blank?
end
# Use only ipv4 interfaces
def local_network_interfaces
network_interfaces_inventory.nil? ? [] : network_interfaces_inventory.network_interfaces(:ipv4)
end
private
def after_init
@listeners << ServerIpAddress.new('0.0.0.0')
end
end
# This is used if bind address is ::, the server name needs to be blank
class AllIpv6Interfaces < AllInterfaces
def self.matches?(opts={})
opts[:bind_address] == '::' && opts[:server_name].blank?
end
# Use only ipv6 interfaces
def local_network_interfaces
network_interfaces_inventory.nil? ? [] : network_interfaces_inventory.network_interfaces(:ipv6)
end
private
def after_init
@listeners << ServerIpAddress.new('::')
end
end
# Used if a bind address is given and the server name is blank
class BindAddressInformation < BasicInformation
def initialize(*args)
super
@listeners << bind_address
@site_addresses << bind_address
end
def self.matches?(opts={})
!opts[:bind_address].blank? && opts[:server_name].blank?
end
# Resolv
def resolve_me(resolver)
@server_name = ServerHostname.new(resolver.names_for(bind_address).first)
@site_addresses << @server_name unless @server_name.blank?
self
end
end
# Use if server name is given and bind address is blank
class ServerNameInformation < BasicInformation
def initialize(*args)
super
@checks << Checks::RequiresBindAddressIfServerNameIsGiven.new
@site_addresses << server_name
end
def resolve_me(resolver)
@bind_address = ServerIpAddress.new(resolver.ips_for(server_name).first)
unless bind_address.blank?
@listeners << bind_address
@site_addresses << bind_address
end
self
end
def self.matches?(opts={})
opts[:bind_address].blank? && !opts[:server_name].blank?
end
end
# Only used if bind address and server name are given and bind address is
# not :: or 0.0.0.0
class BindAddressAndServerNameInformation < BasicInformation
def initialize(*args)
super
@listeners << bind_address
@site_addresses << server_name
@site_addresses << bind_address
@checks << Checks::ServerNameResolvesToBindAddress.new
end
def self.matches?(opts={})
!opts[:bind_address].blank? && !opts[:server_name].blank? && !%w(:: 0.0.0.0).include?(opts[:bind_address])
end
def resolve_me(*); end
end
# If the server name is either an ipv4 or ipv6 address, e.g. 127.0.0.1 or
# ::1, use this one
class ServerNameIsIpInformation < BasicInformation
def initialize(opts={})
super
ip = ServerIpAddress.new(server_name.to_s)
@listeners << ip
@site_addresses << ip
end
def resolve_me(*); end
def self.matches?(opts={})
ip = IPAddr.new(opts[:server_name])
ip.ipv4? || ip.ipv6?
rescue
false
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/server_information_callback_proxy.rb | middleman-core/lib/middleman-core/preview_server/server_information_callback_proxy.rb | module Middleman
class PreviewServer
# This class wraps server information to be used in call back
#
# * listeners
# * port
# * server name
# * site_addresses
#
# All information is "dupped" and the callback is not meant to be used to
# modify these information.
class ServerInformationCallbackProxy
attr_reader :server_name, :port, :site_addresses, :listeners
def initialize(server_information)
@listeners = ServerUrl.new(
hosts: server_information.listeners,
port: server_information.port,
https: server_information.https?,
format_output: false
).to_bind_addresses
@port = server_information.port
@server_name = server_information.server_name.dup unless server_information.server_name.nil?
@site_addresses = ServerUrl.new(
hosts: server_information.site_addresses,
port: server_information.port,
https: server_information.https?,
format_output: false
).to_urls
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/tcp_port_prober.rb | middleman-core/lib/middleman-core/preview_server/tcp_port_prober.rb | module Middleman
class PreviewServer
# Probe for tcp ports
#
# This one first tries `try_port` if this is not available use the free
# port returned by TCPServer.
class TcpPortProber
# Check for port
#
# @param [Integer] try_port
# The port to be checked
#
# @return [Integer]
# The port
def port(try_port)
server = TCPServer.open(try_port)
server.close
try_port
rescue
server = TCPServer.open(0)
port = server.addr[1]
server.close
port
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/server_information.rb | middleman-core/lib/middleman-core/preview_server/server_information.rb | require 'middleman-core/dns_resolver'
require 'middleman-core/preview_server/information'
require 'middleman-core/preview_server/network_interface_inventory'
require 'middleman-core/preview_server/tcp_port_prober'
require 'middleman-core/preview_server/server_information_validator'
module Middleman
class PreviewServer
# This class holds all information which the preview server needs to setup a listener
#
# * server name
# * bind address
# * port
#
# Furthermore it probes for a free tcp port, if the default one 4567 is not available.
class ServerInformation
private
attr_reader :resolver, :validator, :network_interface_inventory, :informations, :tcp_port_prober
public
attr_writer :https
def initialize(opts={})
@resolver = opts.fetch(:resolver, DnsResolver.new)
@validator = opts.fetch(:validator, ServerInformationValidator.new)
@network_interface_inventory = opts.fetch(:network_interface_inventory, NetworkInterfaceInventory.new)
@tcp_port_prober = opts.fetch(:tcp_port_prober, TcpPortProber.new)
@informations = []
@informations << AllInterfaces
@informations << AllIpv4Interfaces
@informations << AllIpv6Interfaces
@informations << ServerNameIsIpInformation
@informations << ServerNameInformation
@informations << BindAddressInformation
@informations << BindAddressAndServerNameInformation
@informations << DefaultInformation
end
# The information
#
# Is cached
def information
return @information if @information
# The `DefaultInformation`-class always returns `true`, so there's
# always a klass available and find will never return nil
listener_klass = informations.find { |l| l.matches? bind_address: @bind_address, server_name: @server_name }
@information = listener_klass.new(bind_address: @bind_address, server_name: @server_name)
@information.show_me_network_interfaces(network_interface_inventory)
@information.resolve_me(resolver)
@information.port = tcp_port_prober.port(@port)
@information.validate_me(validator)
@information
end
# Use a middleman configuration to get information
#
# @param [#[]] config
# The middleman config
def use(config)
@bind_address = config[:bind_address]
@port = config[:port]
@server_name = config[:server_name]
@https = config[:https]
config[:bind_address] = bind_address
config[:port] = port
config[:server_name] = server_name
config[:https] = https?
end
# Make information of internal server class avaible to make debugging
# easier. This can be used to log the class which was used to determine
# the preview server settings
#
# @return [String]
# The name of the class
def handler
information.class.to_s
end
# Is the server information valid?
#
# This is used to output a helpful error message, which can be stored in
# `#reason`.
#
# @return [TrueClass, FalseClass]
# The result
def valid?
information.valid?
end
# The reason why the information is NOT valid
#
# @return [String]
# The reason why the information is not valid
def reason
information.reason
end
# The server name
#
# @return [String]
# The name of the server
def server_name
information.server_name
end
# The bind address of server
#
# @return [String]
# The bind address of the server
def bind_address
information.bind_address
end
# The port on which the server should listen
#
# @return [Integer]
# The port number
def port
information.port
end
# A list of site addresses
#
# @return [Array]
# A list of addresses which can be used to access the middleman preview
# server
def site_addresses
information.site_addresses
end
# A list of listeners
#
# @return [Array]
# A list of bind address where the
def listeners
information.listeners
end
# Is https enabled?
def https?
@https == true
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/network_interface_inventory.rb | middleman-core/lib/middleman-core/preview_server/network_interface_inventory.rb | require 'middleman-core/preview_server/server_ip_address'
module Middleman
class PreviewServer
# This holds information about local network interfaces on the user systemd
class NetworkInterfaceInventory
# Return all ip interfaces
class All
def network_interfaces
ipv4_addresses = Socket.ip_address_list.select(&:ipv4?).map { |ai| ServerIpv4Address.new(ai.ip_address) }
ipv6_addresses = Socket.ip_address_list.select(&:ipv6?).map { |ai| ServerIpv6Address.new(ai.ip_address) }
ipv4_addresses + ipv6_addresses
end
def self.match?(*)
true
end
end
# Return all ipv4 interfaces
class Ipv4
def network_interfaces
Socket.ip_address_list.select { |ai| ai.ipv4? && !ai.ipv4_loopback? }.map { |ai| ServerIpv4Address.new(ai.ip_address) }
end
def self.match?(type)
:ipv4 == type
end
end
# Return all ipv6 interfaces
class Ipv6
def network_interfaces
Socket.ip_address_list.select { |ai| ai.ipv6? && !ai.ipv6_loopback? }.map { |ai| ServerIpv6Address.new(ai.ip_address) }
end
def self.match?(type)
:ipv6 == type
end
end
private
attr_reader :types
public
def initialize
@types = []
@types << Ipv4
@types << Ipv6
@types << All
end
# Return ip interfaces
#
# @param [Symbol] type
# The type of interface which should be returned
def network_interfaces(type=:all)
types.find { |t| t.match? type.to_sym }.new.network_interfaces
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/server_hostname.rb | middleman-core/lib/middleman-core/preview_server/server_hostname.rb | module Middleman
class PreviewServer
class ServerHostname
class ServerFullHostname < SimpleDelegator
def to_s
__getobj__.gsub(/\s/, '+')
end
def self.match?(*)
true
end
alias to_browser to_s
end
class ServerPlainHostname < SimpleDelegator
def to_s
__getobj__.gsub(/\s/, '+') + '.local'
end
def self.match?(name)
name != 'localhost' && /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?\.?$/ === name
end
alias to_browser to_s
end
def self.new(string)
@names = []
@names << ServerPlainHostname
@names << ServerFullHostname
@names.find { |n| n.match? string }.new(string)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/server_information_validator.rb | middleman-core/lib/middleman-core/preview_server/server_information_validator.rb | module Middleman
class PreviewServer
# Validate user input
class ServerInformationValidator
# Validate the input
#
# @param [ServerInformation] information
# The information instance which holds information about the preview
# server settings
#
# @param [Array] checks
# A list of checks which should be evaluated
def validate(information, checks)
checks.each { |c| c.validate information }
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/server_url.rb | middleman-core/lib/middleman-core/preview_server/server_url.rb | require 'ipaddr'
module Middleman
class PreviewServer
# This builds the server urls for the preview server
class ServerUrl
private
attr_reader :hosts, :port, :https, :format_output
public
def initialize(opts={})
@hosts = opts.fetch(:hosts)
@port = opts.fetch(:port)
@https = opts.fetch(:https, false)
@format_output = opts.fetch(:format_output, true)
end
# Return bind addresses
#
# @return [Array]
# List of bind addresses of format host:port
def to_bind_addresses
if format_output
hosts.map { |l| format('"%s:%s"', l.to_s, port) }
else
hosts.map { |l| format('%s:%s', l.to_s, port) }
end
end
# Return server urls
#
# @return [Array]
# List of urls of format http://host:port
def to_urls
if format_output
hosts.map { |l| format('"%s://%s:%s"', https? ? 'https' : 'http', l.to_browser, port) }
else
hosts.map { |l| format('%s://%s:%s', https? ? 'https' : 'http', l.to_browser, port) }
end
end
# Return server config urls
#
# @return [Array]
# List of urls of format http://host:port/__middleman
def to_config_urls
if format_output
hosts.map { |l| format('"%s://%s:%s/__middleman"', https? ? 'https' : 'http', l.to_browser, port) }
else
hosts.map { |l| format('%s://%s:%s/__middleman', https? ? 'https' : 'http', l.to_browser, port) }
end
end
private
def https?
https == true
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server/checks.rb | middleman-core/lib/middleman-core/preview_server/checks.rb | require 'ipaddr'
module Middleman
class PreviewServer
# Checks for input of preview server
module Checks
# This one will get all default setup
class BasicCheck; end
# This checks if the server name resolves to the bind_address
#
# If the users enters:
#
# 1. server_name: www.example.com (10.0.0.1)
# 2. bind_address: 127.0.0.01
#
# This validation will fail
class ServerNameResolvesToBindAddress < BasicCheck
private
attr_reader :resolver
public
def initialize
@resolver = DnsResolver.new
end
# Validate
#
# @param [Information] information
# The information to be validated
def validate(information)
return if resolver.ips_for(information.server_name).include? information.bind_address
information.valid = false
information.reason = format('Server name "%s" does not resolve to bind address "%s"', information.server_name, information.bind_address)
end
end
# This validation fails if the user chooses to use an ip address which is
# not available on his/her system
class InterfaceIsAvailableOnSystem < BasicCheck
# Validate
#
# @param [Information] information
# The information to be validated
def validate(information)
return if information.bind_address.blank? || information.local_network_interfaces.include?(information.bind_address.to_s) || %w(0.0.0.0 ::).any? { |b| information.bind_address == b } || IPAddr.new('127.0.0.0/8').include?(information.bind_address.to_s)
information.valid = false
information.reason = format('Bind address "%s" is not available on your system. Please use one of %s', information.bind_address, information.local_network_interfaces.map { |i| %("#{i}") }.join(', '))
end
end
# This one requires a bind address if the user entered a server name
#
# If the `bind_address` is blank this check will fail
class RequiresBindAddressIfServerNameIsGiven < BasicCheck
def validate(information)
return unless information.bind_address.blank?
information.valid = false
information.reason = format('Server name "%s" does not resolve to an ip address', information.server_name)
end
end
# This validation always fails
class DenyAnyAny < BasicCheck
# Validate
#
# @param [Information] information
# The information to be validated
def validate(information)
information.valid = false
information.reason = 'Undefined combination of options "--server-name" and "--bind-address". If you think this is wrong, please file a bug at "https://github.com/middleman/middleman"'
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/step_definitions/middleman_steps.rb | middleman-core/lib/middleman-core/step_definitions/middleman_steps.rb | require 'fileutils'
Given /^app "([^\"]*)" is using config "([^\"]*)"$/ do |path, config_name|
target = File.join(PROJECT_ROOT_PATH, 'fixtures', path)
config_path = File.join(expand_path("."), "config-#{config_name}.rb")
config_dest = File.join(expand_path("."), 'config.rb')
FileUtils.cp(config_path, config_dest)
end
Given /^an empty app$/ do
step %Q{a directory named "empty_app"}
step %Q{I cd to "empty_app"}
ENV['MM_ROOT'] = nil
end
Given /^a fixture app "([^\"]*)"$/ do |path|
ENV['MM_ROOT'] = nil
# This step can be reentered from several places but we don't want
# to keep re-copying and re-cd-ing into ever-deeper directories
next if File.basename(expand_path(".")) == path
step %Q{a directory named "#{path}"}
target_path = File.join(PROJECT_ROOT_PATH, 'fixtures', path)
FileUtils.cp_r(target_path, expand_path("."))
step %Q{I cd to "#{path}"}
end
Then /^the file "([^\"]*)" has the contents$/ do |path, contents|
write_file(path, contents)
@server_inst.files.poll_once!
end
Then /^the file "([^\"]*)" is removed$/ do |path|
FileUtils.rm(expand_path(path))
@server_inst.files.poll_once!
end
Given /^a modification time for a file named "([^\"]*)"$/ do |file|
target = File.join(expand_path("."), file)
@modification_times[target] = File.mtime(target)
end
Then /^the file "([^\"]*)" should not have been updated$/ do |file|
target = File.join(expand_path("."), file)
expect(File.mtime(target)).to eq(@modification_times[target])
end
# Provide this Aruba overload in case we're matching something with quotes in it
Then /^the file "([^"]*)" should contain '([^']*)'$/ do |file, partial_content|
expect(file).to have_file_content(Regexp.new(Regexp.escape(partial_content)), true)
end
And /the file "(.*)" should be gzipped/ do |file|
expect(File.binread(File.join(expand_path("."), file), 2)).to eq(['1F8B'].pack('H*'))
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/step_definitions/server_steps.rb | middleman-core/lib/middleman-core/step_definitions/server_steps.rb | require 'middleman-core/rack'
require 'rspec/expectations'
require 'capybara/cucumber'
require 'addressable/uri'
Given /^a clean server$/ do
@initialize_commands = []
@activation_commands = []
end
Given /^"([^\"]*)" feature is "([^\"]*)"$/ do |feature, state|
@activation_commands ||= []
if state == 'enabled'
@activation_commands << lambda { activate(feature.to_sym) }
end
end
Given /^"([^\"]*)" feature is "enabled" with "([^\"]*)"$/ do |feature, options_str|
@activation_commands ||= []
options = eval("{#{options_str}}")
@activation_commands << lambda { activate(feature.to_sym, options) }
end
Given /^"([^\"]*)" is set to "([^\"]*)"$/ do |variable, value|
@initialize_commands ||= []
@initialize_commands << lambda {
config[variable.to_sym] = value
}
end
Given /^the Server is running$/ do
root_dir = File.expand_path(expand_path("."))
if File.exist?(File.join(root_dir, 'source'))
ENV['MM_SOURCE'] = 'source'
else
ENV['MM_SOURCE'] = ''
end
ENV['MM_ROOT'] = root_dir
initialize_commands = @initialize_commands || []
activation_commands = @activation_commands || []
@server_inst = ::Middleman::Application.new do
config[:watcher_disable] = true
config[:show_exceptions] = false
initialize_commands.each do |p|
instance_exec(&p)
end
app.after_configuration_eval do
activation_commands.each do |p|
config_context.instance_exec(&p)
end
end
end
Capybara.app = ::Middleman::Rack.new(@server_inst).to_app
end
Given /^the Server is running at "([^\"]*)"$/ do |app_path|
step %Q{a fixture app "#{app_path}"}
step %Q{the Server is running}
end
Given /^a template named "([^\"]*)" with:$/ do |name, string|
step %Q{a file named "source/#{name}" with:}, string
end
Given /^a custom renderer with name "([^\"]*)"$/ do |custom_renderer_name|
# Convert custom renderer class name from CamelCase to snake_case
custom_renderer_filename = custom_renderer_name.gsub(/([A-Z])/, '_\1').downcase.sub(/^_/, '') + '.rb'
target = File.join(PROJECT_ROOT_PATH, 'fixtures', 'custom-renderers', custom_renderer_filename)
require target
end
When /^I go to "([^\"]*)"$/ do |url|
visit(Addressable::URI.encode(url))
end
Then /^going to "([^\"]*)" should not raise an exception$/ do |url|
expect { visit(Addressable::URI.encode(url)) }.to_not raise_exception
end
Then /^the content type should be "([^\"]*)"$/ do |expected|
expect(page.response_headers['Content-Type']).to start_with expected
end
Then /^the "([^\"]*)" header should contain "([^\"]*)"$/ do |header, expected|
expect(page.response_headers[header]).to include expected
end
Then /^I should see "([^\"]*)"$/ do |expected|
expect(page.body).to include expected
end
Then /^I should see '([^\']*)'$/ do |expected|
expect(page.body).to include expected
end
Then /^I should see:$/ do |expected|
expect(page.body).to include expected
end
Then /^I should not see "([^\"]*)"$/ do |expected|
expect(page.body).not_to include expected
end
Then /^I should see content matching %r{(.*)}$/ do |expected|
expect(page.body).to match(expected)
end
Then /^I should not see content matching %r{(.*)}$/ do |expected|
expect(page.body).to_not match(expected)
end
Then /^I should not see:$/ do |expected|
expect(page.body).not_to include expected
end
Then /^the status code should be "([^\"]*)"$/ do |expected|
expect(page.status_code).to eq expected.to_i
end
Then /^I should see "([^\"]*)" lines$/ do |lines|
expect(page.body.chomp.split($/).length).to eq lines.to_i
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/step_definitions/commandline_steps.rb | middleman-core/lib/middleman-core/step_definitions/commandline_steps.rb | When /^I stop (?:middleman|all commands) if the output( of the last command)? contains:$/ do |last_command, expected|
begin
Timeout.timeout(aruba.config.exit_timeout) do
loop do
fail "You need to start middleman interactively first." unless last_command_started
if unescape_text(last_command_started.output) =~ Regexp.new(unescape_text(expected))
all_commands.each { |p| p.terminate }
break
end
sleep 0.1
end
end
rescue ::ChildProcess::TimeoutError, Timeout::Error
last_command_started.terminate
ensure
aruba.announcer.announce :stdout, last_command_started.stdout
aruba.announcer.announce :stderr, last_command_started.stderr
end
end
# Make it just a long running process
Given /`(.*?)` is running in background/ do |cmd|
run_command(cmd, exit_timeout: 120)
end
Given /I have a local hosts file with:/ do |string|
step 'I set the environment variables to:', table(
%(
| variable | value |
| MM_HOSTSRC | .hosts |
)
)
step 'a file named ".hosts" with:', string
end
Given /I start a dns server with:/ do |string|
@dns_server.terminate if defined? @dns_server
port = 5300
db_file = 'dns.db'
step 'I set the environment variables to:', table(
%(
| variable | value |
| MM_DNSRC | 127.0.0.1:#{port}|
)
)
set_environment_variable 'PATH', File.expand_path(File.join(aruba.current_directory, 'bin')) + ':' + ENV['PATH']
write_file db_file, string
@dns_server = run_command("dns_server.rb #{db_file} #{port}", exit_timeout: 120)
end
Given /I start a mdns server with:/ do |string|
@mdns_server.terminate if defined? @mdns_server
port = 5301
db_file = 'mdns.db'
step 'I set the environment variables to:', table(
%(
| variable | value |
| MM_MDNSRC | 127.0.0.1:#{port}|
)
)
set_environment_variable 'PATH', File.expand_path(File.join(aruba.current_directory, 'bin')) + ':' + ENV['PATH']
write_file db_file, string
@mdns_server = run_command("dns_server.rb #{db_file} #{port}", exit_timeout: 120)
end
Given /I start a mdns server for the local hostname/ do
step %(I start a mdns server with:), "#{Socket.gethostname}: 127.0.0.1"
end
# Make sure each and every process is really dead
After do
all_commands.each { |p| p.terminate }
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/step_definitions/builder_steps.rb | middleman-core/lib/middleman-core/step_definitions/builder_steps.rb | require 'fileutils'
Before do
@modification_times = Hash.new
end
Given /^a built app at "([^\"]*)"$/ do |path|
step %Q{a fixture app "#{path}"}
step %Q{I run `middleman build --verbose`}
end
Given /^was successfully built$/ do
step %Q{the output should contain "Project built successfully."}
step %Q{the exit status should be 0}
step %Q{a directory named "build" should exist}
end
Given /^a successfully built app at "([^\"]*)"$/ do |path|
step %Q{a built app at "#{path}"}
step %Q{was successfully built}
end
Given /^a built app at "([^\"]*)" with flags "([^\"]*)"$/ do |path, flags|
step %Q{a fixture app "#{path}"}
step %Q{I run `middleman build #{flags}`}
end
Given /^a successfully built app at "([^\"]*)" with flags "([^\"]*)"$/ do |path, flags|
step %Q{a built app at "#{path}" with flags "#{flags}"}
step %Q{was successfully built}
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/meta_pages/sitemap_tree.rb | middleman-core/lib/middleman-core/meta_pages/sitemap_tree.rb | require 'middleman-core/meta_pages/sitemap_resource'
module Middleman
module MetaPages
# View class for a sitemap tree
class SitemapTree
def initialize
@children = {}
end
def add_resource(resource)
add_path(resource.path.split('/'), resource)
end
def render
sorted_children_keys = @children.keys.sort do |a, b|
a_subtree = @children[a]
b_subtree = @children[b]
if a_subtree.is_a? SitemapResource
if b_subtree.is_a? SitemapResource
a.downcase <=> b.downcase
else
1
end
elsif b_subtree.is_a? SitemapResource
if a_subtree.is_a? SitemapResource
b.downcase <=> a.downcase
else
-1
end
else
a.downcase <=> b.downcase
end
end
sorted_children_keys.reduce('') do |content, path_part|
subtree = @children[path_part]
content << "<details class='#{subtree.css_classes.join(' ')}'>"
content << '<summary>'
content << "<i class='icon-folder-open'></i>" unless subtree.is_a? SitemapResource
content << "#{path_part}</summary>"
content << subtree.render
content << '</details>'
end
end
def css_classes
['tree'].concat(ignored? ? ['ignored'] : [])
end
def ignored?
@children.values.all?(&:ignored?)
end
protected
def add_path(path_parts, resource)
first_part = path_parts.first
if path_parts.size == 1
sitemap_class = SitemapResource
# Allow special sitemap resources to use custom metadata view calsses
sitemap_class = resource.meta_pages_class if resource.respond_to? :meta_pages_class
@children[first_part] = sitemap_class.new(resource)
else
@children[first_part] ||= SitemapTree.new
@children[first_part].add_path(path_parts[1..-1], resource)
end
end
def to_s
'Sitemap Tree'
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/meta_pages/config_setting.rb | middleman-core/lib/middleman-core/meta_pages/config_setting.rb | require 'pp'
module Middleman
module MetaPages
# View class for a config entry
class ConfigSetting
include Padrino::Helpers::OutputHelpers
include Padrino::Helpers::TagHelpers
def initialize(setting)
@setting = setting
end
def render
content = ''
key_classes = ['key']
key_classes << 'modified' if @setting.value_set?
content << content_tag(:span, @setting.key.pretty_inspect.strip, class: key_classes.join(' '))
content << ' = '
content << content_tag(:span, @setting.value.pretty_inspect.strip, class: 'value')
if @setting.default && @setting.value_set? && @setting.default != @setting.value
content << content_tag(:span, class: 'default') do
"(Default: #{@setting.default.inspect})"
end
end
if @setting.description
content << content_tag(:p, class: 'description') do
@setting.description
end
end
content
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/meta_pages/sitemap_resource.rb | middleman-core/lib/middleman-core/meta_pages/sitemap_resource.rb | require 'padrino-helpers'
require 'padrino-helpers/output_helpers'
require 'padrino-helpers/tag_helpers'
module Middleman
module MetaPages
# View class for a sitemap resource
class SitemapResource
include Padrino::Helpers::OutputHelpers
include Padrino::Helpers::TagHelpers
def initialize(resource)
@resource = resource
end
def render
classes = 'resource-details'
classes << ' ignored' if @resource.ignored?
content_tag :div, class: classes do
content_tag :table do
content = ''
resource_properties.each do |label, value|
content << content_tag(:tr) do
row_content = ''
row_content << content_tag(:th, label)
row_content << content_tag(:td, value)
row_content.html_safe
end
end
content.html_safe
end
end
end
# A hash of label to value for all the properties we want to display
def resource_properties
props = {}
props['Path'] = @resource.path
build_path = @resource.destination_path
build_path = 'Not built' if ignored?
props['Build Path'] = build_path if @resource.path != build_path
props['URL'] = content_tag(:a, @resource.url, href: @resource.url) unless ignored?
props['Source File'] = @resource.file_descriptor ? @resource.file_descriptor[:full_path].to_s.sub(/^#{Regexp.escape(ENV['MM_ROOT'] + '/')}/, '') : 'Dynamic'
data = @resource.data
props['Data'] = data.to_hash(symbolize_keys: true).inspect unless data.empty?
options = @resource.options
props['Options'] = options.inspect unless options.empty?
locals = @resource.locals.keys
props['Locals'] = locals.join(', ') unless locals.empty?
props
end
def ignored?
@resource.ignored?
end
def css_classes
['resource'].concat(ignored? ? ['ignored'] : [])
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/init.rb | init.rb | # frozen_string_literal: true
require 'cancan'
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/matchers.rb | spec/matchers.rb | # frozen_string_literal: true
RSpec::Matchers.define :orderlessly_match do |original_string|
match do |given_string|
original_string.split('').sort == given_string.split('').sort
end
failure_message do |given_string|
"expected \"#{given_string}\" to have the same characters as \"#{original_string}\""
end
failure_message_when_negated do |given_string|
"expected \"#{given_string}\" not to have the same characters as \"#{original_string}\""
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/changelog_spec.rb | spec/changelog_spec.rb | # frozen_string_literal: true
# credits to https://github.com/rubocop-hq/rubocop for this CHANGELOG checker
RSpec.describe 'changelog' do
subject(:changelog) do
path = File.join(File.dirname(__FILE__), '..', 'CHANGELOG.md')
File.read(path)
end
it 'has newline at end of file' do
expect(changelog.end_with?("\n")).to be true
end
it 'has link definitions for all implicit links' do
implicit_link_names = changelog.scan(/\[([^\]]+)\]\[\]/).flatten.uniq
implicit_link_names.each do |name|
expect(changelog).to include("[#{name}]: http")
end
end
describe 'entry' do
subject(:entries) { lines.grep(/^\*/).map(&:chomp) }
let(:lines) { changelog.each_line }
it 'has a whitespace between the * and the body' do
expect(entries).to all(match(/^\* \S/))
end
context 'after version 1.17.0' do
let(:lines) do
changelog.each_line.take_while do |line|
!line.start_with?('## 1.17.0')
end
end
it 'has a link to the contributors at the end' do
expect(entries).to all(match(/\(\[@\S+\]\[\](?:, \[@\S+\]\[\])*\)$/))
end
end
describe 'link to related issue' do
let(:issues) do
entries.map do |entry|
entry.match(/\[(?<number>[#\d]+)\]\((?<url>[^\)]+)\)/)
end.compact
end
it 'has an issue number prefixed with #' do
issues.each do |issue|
expect(issue[:number]).to match(/^#\d+$/)
end
end
it 'has a valid URL' do
issues.each do |issue|
number = issue[:number].gsub(/\D/, '')
pattern = %r{^https://github\.com/CanCanCommunity/cancancan/(?:issues|pull)/#{number}$}
expect(issue[:url]).to match(pattern)
end
end
it 'has a colon and a whitespace at the end' do
entries_including_issue_link = entries.select do |entry|
entry.match(/^\*\s*\[/)
end
expect(entries_including_issue_link).to all(include('): '))
end
end
describe 'contributor name' do
subject(:contributor_names) { lines.grep(/\A\[@/).map(&:chomp) }
it 'has a unique contributor name' do
expect(contributor_names.uniq.size).to eq contributor_names.size
end
end
describe 'body' do
let(:bodies) do
entries.map do |entry|
entry
.gsub(/`[^`]+`/, '``')
.sub(/^\*\s*(?:\[.+?\):\s*)?/, '')
.sub(/\s*\([^\)]+\)$/, '')
end
end
it 'does not start with a lower case' do
bodies.each do |body|
expect(body).not_to match(/^[a-z]/)
end
end
it 'ends with a punctuation' do
expect(bodies).to all(match(/[\.\!]$/))
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
Bundler.require
require 'matchers'
require 'cancan/matchers'
# I8n setting to fix deprecation.
I18n.enforce_available_locales = false if defined?(I18n) && I18n.respond_to?('enforce_available_locales=')
# Add support to load paths
$LOAD_PATH.unshift File.expand_path('support', __dir__)
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
RSpec.configure do |config|
config.filter_run focus: true
config.run_all_when_everything_filtered = true
config.disable_monkey_patching = true
config.mock_with :rspec
config.order = 'random'
config.expect_with :rspec do |c|
c.syntax = :expect
end
config.include SQLHelpers
config.after :each do
CanCan.accessible_by_strategy = CanCan.default_accessible_by_strategy
CanCan.rules_compressor_enabled = true
end
end
RSpec::Matchers.define :generate_sql do |expected|
match do |actual|
normalized_sql(actual) == expected.gsub(/\s+/, ' ').strip
end
failure_message do |actual|
"Returned sql:\n#{normalized_sql(actual)}\ninstead of:\n#{expected.gsub(/\s+/, ' ').strip}"
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/support/ability.rb | spec/support/ability.rb | # frozen_string_literal: true
class Ability
include CanCan::Ability
def initialize(user)
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/support/sql_helpers.rb | spec/support/sql_helpers.rb | # frozen_string_literal: true
module SQLHelpers
def normalized_sql(adapter)
adapter.database_records.to_sql.strip.squeeze(' ')
end
def sqlite?
ENV['DB'] == 'sqlite'
end
def postgres?
ENV['DB'] == 'postgres'
end
def connect_db
# ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Base.logger = nil
if sqlite?
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
elsif postgres?
connect_postgres
elsif ENV['DB'].nil?
raise StandardError, "ENV['DB'] not specified"
else
raise StandardError, "database not supported: #{ENV['DB']}. Try DB='sqlite' or DB='postgres'"
end
end
private
def connect_postgres
ActiveRecord::Base.establish_connection(adapter: 'postgresql', host: 'localhost',
database: 'postgres', schema_search_path: 'public',
user: 'postgres', password: 'postgres')
ActiveRecord::Base.connection.drop_database('cancan_postgresql_spec')
ActiveRecord::Base.connection.create_database('cancan_postgresql_spec', 'encoding' => 'utf-8',
'adapter' => 'postgresql')
ActiveRecord::Base.establish_connection(adapter: 'postgresql', host: 'localhost',
database: 'cancan_postgresql_spec',
user: 'postgres', password: 'postgres')
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/rule_spec.rb | spec/cancan/rule_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'ostruct' # for OpenStruct below
# Most of Rule functionality is tested in Ability specs
RSpec.describe CanCan::Rule do
before(:each) do
@conditions = {}
@rule = CanCan::Rule.new(true, :read, Integer, @conditions)
end
it 'returns no association joins if none exist' do
expect(@rule.associations_hash).to eq({})
end
it 'returns no association for joins if just attributes' do
@conditions[:foo] = :bar
expect(@rule.associations_hash).to eq({})
end
it 'returns single association for joins' do
@conditions[:foo] = { bar: 1 }
expect(@rule.associations_hash).to eq(foo: {})
end
it 'returns multiple associations for joins' do
@conditions[:foo] = { bar: 1 }
@conditions[:test] = { 1 => 2 }
expect(@rule.associations_hash).to eq(foo: {}, test: {})
end
it 'returns nested associations for joins' do
@conditions[:foo] = { bar: { 1 => 2 } }
expect(@rule.associations_hash).to eq(foo: { bar: {} })
end
it 'returns no association joins if conditions is nil' do
rule = CanCan::Rule.new(true, :read, Integer, nil)
expect(rule.associations_hash).to eq({})
end
it 'allows nil in attribute spot for edge cases' do
rule1 = CanCan::Rule.new(true, :action, :subject, nil, :var)
expect(rule1.attributes).to eq []
expect(rule1.conditions).to eq :var
rule2 = CanCan::Rule.new(true, :action, :subject, nil, %i[foo bar])
expect(rule2.attributes).to eq []
expect(rule2.conditions).to eq %i[foo bar]
end
unless RUBY_ENGINE == 'jruby'
describe '#inspect' do
def count_queries(&block)
count = 0
counter_f = lambda { |_name, _started, _finished, _unique_id, payload|
count += 1 unless payload[:name].in? %w[CACHE SCHEMA]
}
ActiveSupport::Notifications.subscribed(counter_f, 'sql.active_record', &block)
count
end
before do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:watermelons) do |t|
t.boolean :visible
end
end
class Watermelon < ActiveRecord::Base
scope :visible, -> { where(visible: true) }
end
end
it 'does not evaluate the conditions when they are scopes' do
rule = CanCan::Rule.new(true, :read, Watermelon, Watermelon.visible, {}, {})
count = count_queries { rule.inspect }
expect(count).to eq 0
end
it 'displays the rule correctly when it is constructed through sql array' do
rule = CanCan::Rule.new(true, :read, Watermelon, ['visible=?', true], {}, {})
expect(rule.inspect).not_to be_blank
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/controller_resource_spec.rb | spec/cancan/controller_resource_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe CanCan::ControllerResource do
let(:ability) { Ability.new(nil) }
let(:params) { HashWithIndifferentAccess.new(controller: 'models') }
let(:controller_class) { Class.new }
let(:controller) { controller_class.new }
before(:each) do
class Model
attr_accessor :name
def initialize(attributes = {})
attributes.each do |attribute, value|
send("#{attribute}=", value)
end
end
end
allow(controller).to receive(:params) { params }
allow(controller).to receive(:current_ability) { ability }
allow(controller_class).to receive(:cancan_skipper) { { authorize: {}, load: {} } }
end
context 'on build actions' do
before :each do
params.merge!(action: 'new')
end
it 'builds a new resource with attributes from current ability' do
ability.can(:create, Model, name: 'from conditions')
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('from conditions')
end
it 'overrides initial attributes with params' do
params[:model] = { name: 'from params' }
ability.can(:create, Model, name: 'from conditions')
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('from params')
end
it 'builds a resource when on custom new action even when params[:id] exists' do
params.merge!(action: 'build', id: '123')
allow(Model).to receive(:new) { :some_model }
resource = CanCan::ControllerResource.new(controller, new: :build)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it 'only authorizes :show action on parent resource' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
params[:model_id] = 123
allow(controller).to receive(:authorize!).with(:show, model) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller, :model, parent: true)
expect { resource.load_and_authorize_resource }.to raise_error(CanCan::AccessDenied)
end
end
context 'on create actions' do
before :each do
params.merge!(action: 'create')
end
# Rails includes namespace in params, see issue #349
it 'creates through the namespaced params' do
module MyEngine
class Model < ::Model; end
end
params.merge!(controller: 'my_engine/models', my_engine_model: { name: 'foobar' })
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('foobar')
end
it 'builds a new resource with hash if params[:id] is not specified' do
params[:model] = { name: 'foobar' }
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('foobar')
end
it 'builds a new resource for namespaced model with hash if params[:id] is not specified' do
module Sub
class Model < ::Model; end
end
params['sub_model'] = { name: 'foobar' }
resource = CanCan::ControllerResource.new(controller, class: ::Sub::Model)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('foobar')
end
context 'params[:id] is not specified' do
it 'builds a new resource for namespaced controller and namespaced model with hash' do
params.merge!(:controller => 'admin/sub_models', 'sub_model' => { name: 'foobar' })
resource = CanCan::ControllerResource.new(controller, class: Model)
resource.load_resource
expect(controller.instance_variable_get(:@sub_model).name).to eq('foobar')
end
end
it 'builds a new resource for namespaced controller given through folder format' do
module Admin
module SubModule
class HiddenModel < ::Model; end
end
end
params[:controller] = 'admin/sub_module/hidden_models'
resource = CanCan::ControllerResource.new(controller)
expect { resource.load_resource }.not_to raise_error
end
context 'with :singleton option' do
it 'does not build record through has_one association because it can cause it to delete it in the database' do
category = Class.new
allow_any_instance_of(Model).to receive('category=').with(category)
allow_any_instance_of(Model).to receive('category') { category }
params[:model] = { name: 'foobar' }
controller.instance_variable_set(:@category, category)
resource = CanCan::ControllerResource.new(controller, through: :category, singleton: true)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('foobar')
expect(controller.instance_variable_get(:@model).category).to eq(category)
end
end
it 'builds record through has_one association with :singleton and :shallow options' do
params[:model] = { name: 'foobar' }
resource = CanCan::ControllerResource.new(controller, through: :category, singleton: true, shallow: true)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq('foobar')
end
context 'with a strong parameters method' do
before :each do
params.merge!(controller: 'model', model: { name: 'test' })
end
it 'accepts and uses the specified symbol for sanitizing input' do
allow(controller).to receive(:resource_params).and_return(resource: 'params')
allow(controller).to receive(:model_params).and_return(model: 'params')
allow(controller).to receive(:create_params).and_return(create: 'params')
allow(controller).to receive(:custom_params).and_return(custom: 'params')
resource = CanCan::ControllerResource.new(controller, param_method: :custom_params)
expect(resource.send('resource_params')).to eq(custom: 'params')
end
it 'accepts the specified string for sanitizing input' do
resource = CanCan::ControllerResource.new(controller, param_method: "{:custom => 'params'}")
expect(resource.send('resource_params')).to eq(custom: 'params')
end
it 'accepts the specified proc for sanitizing input' do
resource = CanCan::ControllerResource.new(controller, param_method: proc { |_c| { custom: 'params' } })
expect(resource.send('resource_params')).to eq(custom: 'params')
end
it 'prefers to use the create_params method for sanitizing input' do
allow(controller).to receive(:resource_params).and_return(resource: 'params')
allow(controller).to receive(:model_params).and_return(model: 'params')
allow(controller).to receive(:create_params).and_return(create: 'params')
allow(controller).to receive(:custom_params).and_return(custom: 'params')
resource = CanCan::ControllerResource.new(controller)
expect(resource.send('resource_params')).to eq(create: 'params')
end
it 'prefers to use the <model_name>_params method for sanitizing input if create is not found' do
allow(controller).to receive(:resource_params).and_return(resource: 'params')
allow(controller).to receive(:model_params).and_return(model: 'params')
allow(controller).to receive(:custom_params).and_return(custom: 'params')
resource = CanCan::ControllerResource.new(controller)
expect(resource.send('resource_params')).to eq(model: 'params')
end
it 'prefers to use the resource_params method for sanitizing input if create or model is not found' do
allow(controller).to receive(:resource_params).and_return(resource: 'params')
allow(controller).to receive(:custom_params).and_return(custom: 'params')
resource = CanCan::ControllerResource.new(controller)
expect(resource.send('resource_params')).to eq(resource: 'params')
end
end
end
context 'on collection actions' do
before :each do
params[:action] = 'index'
end
it 'builds a collection when on index action when class responds to accessible_by' do
allow(Model).to receive(:accessible_by).with(ability, :index) { :found_models }
resource = CanCan::ControllerResource.new(controller, :model)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
expect(controller.instance_variable_get(:@models)).to eq(:found_models)
end
it 'does not build a collection when on index action when class does not respond to accessible_by' do
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
expect(controller.instance_variable_defined?(:@models)).to be(false)
end
it 'does not use accessible_by when defining abilities through a block' do
allow(Model).to receive(:accessible_by).with(ability) { :found_models }
ability.can(:read, Model) { |_p| false }
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
expect(controller.instance_variable_defined?(:@models)).to be(false)
end
it 'does not authorize single resource in collection action' do
allow(controller).to receive(:authorize!).with(:index, Model) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
it 'authorizes parent resource in collection action' do
controller.instance_variable_set(:@category, :some_category)
allow(controller).to receive(:authorize!).with(:show, :some_category) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller, :category, parent: true)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
it 'authorizes with :custom_action for parent collection action' do
controller.instance_variable_set(:@category, :some_category)
allow(controller).to receive(:authorize!).with(:custom_action, :some_category) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller, :category, parent: true, parent_action: :custom_action)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
it 'has the specified nested resource_class when using / for namespace' do
module Admin
class Dashboard; end
end
ability.can(:index, 'admin/dashboard')
params[:controller] = 'admin/dashboard'
resource = CanCan::ControllerResource.new(controller, authorize: true)
expect(resource.send(:resource_class)).to eq(Admin::Dashboard)
end
it 'does not build a single resource when on custom collection action even with id' do
params.merge!(action: 'sort', id: '123')
resource = CanCan::ControllerResource.new(controller, collection: %i[sort list])
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
end
it 'loads a collection resource when on custom action with no id param' do
allow(Model).to receive(:accessible_by).with(ability, :sort) { :found_models }
params[:action] = 'sort'
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
expect(controller.instance_variable_get(:@models)).to eq(:found_models)
end
it 'loads parent resource through proper id parameter' do
model = Model.new
allow(Model).to receive(:find).with('1') { model }
params.merge!(controller: 'categories', model_id: 1)
resource = CanCan::ControllerResource.new(controller, :model)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'authorizes nested resource through parent association on index action' do
controller.instance_variable_set(:@category, category = double)
allow(controller).to receive(:authorize!).with(:index, { category => Model }) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller, through: :category)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
end
context 'on instance read actions' do
before :each do
params.merge!(action: 'show', id: '123')
end
it 'loads the resource into an instance variable if params[:id] is specified' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'does not load resource into an instance variable if already set' do
controller.instance_variable_set(:@model, :some_model)
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it 'loads resource for namespaced controller' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
params[:controller] = 'admin/models'
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'performs authorization using controller action and loaded model' do
controller.instance_variable_set(:@model, :some_model)
allow(controller).to receive(:authorize!).with(:show, :some_model) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
it 'performs authorization using controller action and non loaded model' do
allow(controller).to receive(:authorize!).with(:show, Model) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
it 'calls load_resource and authorize_resource for load_and_authorize_resource' do
resource = CanCan::ControllerResource.new(controller)
expect(resource).to receive(:load_resource)
expect(resource).to receive(:authorize_resource)
resource.load_and_authorize_resource
end
it 'loads resource through the association of another parent resource using instance variable' do
category = double(models: {})
controller.instance_variable_set(:@category, category)
allow(category.models).to receive(:find).with('123') { :some_model }
resource = CanCan::ControllerResource.new(controller, through: :category)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it 'loads resource through the custom association name' do
category = double(custom_models: {})
controller.instance_variable_set(:@category, category)
allow(category.custom_models).to receive(:find).with('123') { :some_model }
resource = CanCan::ControllerResource.new(controller, through: :category, through_association: :custom_models)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it 'loads resource through the association of another parent resource using method' do
category = double(models: {})
allow(controller).to receive(:category) { category }
allow(category.models).to receive(:find).with('123') { :some_model }
resource = CanCan::ControllerResource.new(controller, through: :category)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it "does not load through parent resource if instance isn't loaded when shallow" do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
resource = CanCan::ControllerResource.new(controller, through: :category, shallow: true)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'raises AccessDenied when attempting to load resource through nil' do
resource = CanCan::ControllerResource.new(controller, through: :category)
expect do
resource.load_resource
end.to raise_error(CanCan::AccessDenied) { |exception|
expect(exception.action).to eq(:show)
expect(exception.subject).to eq(Model)
}
expect(controller.instance_variable_get(:@model)).to be_nil
end
it 'loads through first matching if multiple are given' do
category = double(models: {})
controller.instance_variable_set(:@category, category)
allow(category.models).to receive(:find).with('123') { :some_model }
resource = CanCan::ControllerResource.new(controller, through: %i[category user])
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it 'finds record through has_one association with :singleton option without id param' do
params[:id] = nil
category = double(model: :some_model)
controller.instance_variable_set(:@category, category)
resource = CanCan::ControllerResource.new(controller, through: :category, singleton: true)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(:some_model)
end
it 'does not try to load resource for other action if params[:id] is undefined' do
params.merge!(action: 'list', id: nil)
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
end
it 'does not try to load resource for other action if params[:id] is blank' do
params.merge!(action: 'list', id: '')
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to be_nil
end
it 'finds record through has_one association with :singleton and :shallow options' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
resource = CanCan::ControllerResource.new(controller, through: :category, singleton: true, shallow: true)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'loads the model using a custom class' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
resource = CanCan::ControllerResource.new(controller, class: Model)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'loads the model using a custom namespaced class' do
module Sub
class Model < ::Model; end
end
model = Sub::Model.new
allow(Sub::Model).to receive(:find).with('123') { model }
resource = CanCan::ControllerResource.new(controller, class: ::Sub::Model)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'authorizes based on resource name if class is false' do
allow(controller).to receive(:authorize!).with(:show, :model) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller, class: false)
expect { resource.authorize_resource }.to raise_error(CanCan::AccessDenied)
end
it 'loads and authorize using custom instance name' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
allow(controller).to receive(:authorize!).with(:show, model) { raise CanCan::AccessDenied }
resource = CanCan::ControllerResource.new(controller, instance_name: :custom_model)
expect { resource.load_and_authorize_resource }.to raise_error(CanCan::AccessDenied)
expect(controller.instance_variable_get(:@custom_model)).to eq(model)
end
it 'loads resource using custom ID param' do
model = Model.new
allow(Model).to receive(:find).with('123') { model }
params[:the_model] = 123
resource = CanCan::ControllerResource.new(controller, id_param: :the_model)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
# CVE-2012-5664
it 'always converts id param to string' do
params[:the_model] = { malicious: 'I am' }
resource = CanCan::ControllerResource.new(controller, id_param: :the_model)
expect(resource.send(:id_param).class).to eq(String)
end
it 'should id param return nil if param is nil' do
params[:the_model] = nil
resource = CanCan::ControllerResource.new(controller, id_param: :the_model)
expect(resource.send(:id_param)).to be_nil
end
it 'loads resource using ActiveRecord find_by method' do
model = Model.new
allow(Model).to receive(:name).with('foo') { model }
params.merge!(action: 'show', id: 'foo')
resource = CanCan::ControllerResource.new(controller, find_by: :name)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'loads resource using custom find_by method' do
model = Model.new
allow(Model).to receive(:find_by).with(name: 'foo') { model }
params.merge!(action: 'show', id: 'foo')
resource = CanCan::ControllerResource.new(controller, find_by: :name)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'loads resource using dynamic finder method' do
model = Model.new
allow(Model).to receive(:find_by_name!).with('foo') { model }
params.merge!(action: 'show', id: 'foo')
resource = CanCan::ControllerResource.new(controller, find_by: :name)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
it 'allows full find method to be passed into find_by option' do
model = Model.new
allow(Model).to receive(:find_by_name).with('foo') { model }
params.merge!(action: 'show', id: 'foo')
resource = CanCan::ControllerResource.new(controller, find_by: :find_by_name)
resource.load_resource
expect(controller.instance_variable_get(:@model)).to eq(model)
end
end
context 'when @name passed as symbol' do
it 'returns namespaced #resource_class' do
module Admin; end
class Admin::Dashboard; end
params[:controller] = 'admin/dashboard'
resource = CanCan::ControllerResource.new(controller, :dashboard)
expect(resource.send(:resource_class)).to eq Admin::Dashboard
end
end
it 'calls the sanitizer when the parameter hash matches our object' do
params.merge!(action: 'create', model: { name: 'test' })
allow(controller).to receive(:create_params).and_return({})
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq nil
end
it 'sanitizes correctly when the instance name is overridden' do
params.merge!(action: 'create', custom_name: { name: 'foobar' })
allow(controller).to receive(:create_params).and_return({})
resource = CanCan::ControllerResource.new(controller, instance_name: :custom_name)
resource.load_resource
expect(controller.instance_variable_get(:@custom_name).name).to eq nil
end
it 'calls the sanitize method on non-save actions when required' do
params.merge!(action: 'new', model: { name: 'test' })
allow(controller).to receive(:resource_params).and_return({})
resource = CanCan::ControllerResource.new(controller)
resource.load_resource
expect(controller.instance_variable_get(:@model).name).to eq nil
end
it "doesn't sanitize parameters on non-save actions when not required" do
params.merge!(action: 'new', not_our_model: { name: 'test' })
allow(controller).to receive(:resource_params).and_raise
resource = CanCan::ControllerResource.new(controller)
expect do
resource.load_resource
end.to_not raise_error
end
it "is a parent resource when name is provided which doesn't match controller" do
resource = CanCan::ControllerResource.new(controller, :category)
expect(resource).to be_parent
end
it 'does not be a parent resource when name is provided which matches controller' do
resource = CanCan::ControllerResource.new(controller, :model)
expect(resource).to_not be_parent
end
it 'is parent if specified in options' do
resource = CanCan::ControllerResource.new(controller, :model, parent: true)
expect(resource).to be_parent
end
it 'does not be parent if specified in options' do
resource = CanCan::ControllerResource.new(controller, :category, parent: false)
expect(resource).to_not be_parent
end
it "has the specified resource_class if 'name' is passed to load_resource" do
class Section; end
resource = CanCan::ControllerResource.new(controller, :section)
expect(resource.send(:resource_class)).to eq(Section)
end
it 'skips resource behavior for :only actions in array' do
allow(controller_class).to receive(:cancan_skipper) { { load: { nil => { only: %i[index show] } } } }
params[:action] = 'index'
expect(CanCan::ControllerResource.new(controller).skip?(:load)).to be(true)
expect(CanCan::ControllerResource.new(controller, :some_resource).skip?(:load)).to be(false)
params[:action] = 'show'
expect(CanCan::ControllerResource.new(controller).skip?(:load)).to be(true)
params[:action] = 'other_action'
expect(CanCan::ControllerResource.new(controller).skip?(:load)).to be_falsey
end
it 'skips resource behavior for :only one action on resource' do
allow(controller_class).to receive(:cancan_skipper) { { authorize: { model: { only: :index } } } }
params[:action] = 'index'
expect(CanCan::ControllerResource.new(controller).skip?(:authorize)).to be(false)
expect(CanCan::ControllerResource.new(controller, :model).skip?(:authorize)).to be(true)
params[:action] = 'other_action'
expect(CanCan::ControllerResource.new(controller, :model).skip?(:authorize)).to be_falsey
end
it 'skips resource behavior :except actions in array' do
allow(controller_class).to receive(:cancan_skipper) { { load: { nil => { except: %i[index show] } } } }
params[:action] = 'index'
expect(CanCan::ControllerResource.new(controller).skip?(:load)).to be_falsey
params[:action] = 'show'
expect(CanCan::ControllerResource.new(controller).skip?(:load)).to be_falsey
params[:action] = 'other_action'
expect(CanCan::ControllerResource.new(controller).skip?(:load)).to be(true)
expect(CanCan::ControllerResource.new(controller, :some_resource).skip?(:load)).to be(false)
end
it 'skips resource behavior :except one action on resource' do
allow(controller_class).to receive(:cancan_skipper) { { authorize: { model: { except: :index } } } }
params[:action] = 'index'
expect(CanCan::ControllerResource.new(controller, :model).skip?(:authorize)).to be_falsey
params[:action] = 'other_action'
expect(CanCan::ControllerResource.new(controller).skip?(:authorize)).to be(false)
expect(CanCan::ControllerResource.new(controller, :model).skip?(:authorize)).to be(true)
end
it 'skips loading and authorization' do
allow(controller_class).to receive(:cancan_skipper) { { authorize: { nil => {} }, load: { nil => {} } } }
params[:action] = 'new'
resource = CanCan::ControllerResource.new(controller)
expect { resource.load_and_authorize_resource }.not_to raise_error
expect(controller.instance_variable_get(:@model)).to be_nil
end
context 'when model name is Action' do
let(:action_params) { HashWithIndifferentAccess.new(controller: 'actions') }
let(:action_controller_class) { Class.new }
let(:action_controller) { controller_class.new }
before :each do
class Action
attr_accessor :name
def initialize(attributes = {})
attributes.each do |attribute, value|
send("#{attribute}=", value)
end
end
end
allow(action_controller).to receive(:params) { action_params }
allow(action_controller).to receive(:current_ability) { ability }
allow(action_controller_class).to receive(:cancan_skipper) { { authorize: {}, load: {} } }
end
it 'builds a new resource with attributes from current ability' do
action_params[:action] = 'new'
ability.can(:create, Action, name: 'from conditions')
resource = CanCan::ControllerResource.new(action_controller)
resource.load_resource
expect(action_controller.instance_variable_get(:@action).name).to eq('from conditions')
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/exceptions_spec.rb | spec/cancan/exceptions_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe CanCan::AccessDenied do
describe 'with action, subject, and conditions' do
before(:each) do
@exception = CanCan::AccessDenied.new(nil, :some_action, :some_subject, :some_conditions)
end
it 'has action, subject, and conditions accessors' do
expect(@exception.action).to eq(:some_action)
expect(@exception.subject).to eq(:some_subject)
expect(@exception.conditions).to eq(:some_conditions)
end
it 'has a changeable default message' do
expect(@exception.message).to eq('You are not authorized to access this page.')
@exception.default_message = 'Unauthorized!'
expect(@exception.message).to eq('Unauthorized!')
end
it 'has debug information on inspect' do
expect(@exception.inspect).to eq(
'#<CanCan::AccessDenied action: :some_action, subject: :some_subject, conditions: :some_conditions>'
)
end
end
describe 'with only a message' do
before(:each) do
@exception = CanCan::AccessDenied.new('Access denied!')
end
it 'has nil action, subject, and conditions' do
expect(@exception.action).to be_nil
expect(@exception.subject).to be_nil
expect(@exception.conditions).to be_nil
end
it 'has passed message' do
expect(@exception.message).to eq('Access denied!')
end
end
describe 'i18n in the default message' do
after(:each) do
I18n.backend = nil
end
it 'uses i18n for the default message' do
I18n.backend.store_translations :en, unauthorized: { default: 'This is a different message' }
@exception = CanCan::AccessDenied.new
expect(@exception.message).to eq('This is a different message')
end
it 'defaults to a nice message' do
@exception = CanCan::AccessDenied.new
expect(@exception.message).to eq('You are not authorized to access this page.')
end
it 'does not use translation if a message is given' do
@exception = CanCan::AccessDenied.new("Hey! You're not welcome here")
expect(@exception.message).to eq("Hey! You're not welcome here")
expect(@exception.message).to_not eq('You are not authorized to access this page.')
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/controller_additions_spec.rb | spec/cancan/controller_additions_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe CanCan::ControllerAdditions do
before(:each) do
@controller_class = Class.new
@controller = @controller_class.new
allow(@controller).to receive(:params) { {} }
allow(@controller).to receive(:current_user) { :current_user }
expect(@controller_class).to receive(:helper_method).with(:can?, :cannot?, :current_ability)
@controller_class.send(:include, CanCan::ControllerAdditions)
end
it 'authorize! assigns @_authorized instance variable and pass args to current ability' do
allow(@controller.current_ability).to receive(:authorize!).with(:foo, :bar)
@controller.authorize!(:foo, :bar)
expect(@controller.instance_variable_get(:@_authorized)).to be(true)
end
it 'has a current_ability method which generates an ability for the current user' do
expect(@controller.current_ability).to be_kind_of(Ability)
end
it 'provides a can? and cannot? methods which go through the current ability' do
expect(@controller.current_ability).to be_kind_of(Ability)
expect(@controller.can?(:foo, :bar)).to be(false)
expect(@controller.cannot?(:foo, :bar)).to be(true)
end
it 'load_and_authorize_resource setups a before filter which passes call to ControllerResource' do
expect(cancan_resource_class = double).to receive(:load_and_authorize_resource)
allow(CanCan::ControllerResource).to receive(:new).with(@controller, nil, { foo: :bar }) { cancan_resource_class }
expect(@controller_class)
.to receive(:before_action).with({}) { |_options, &block| block.call(@controller) }
@controller_class.load_and_authorize_resource foo: :bar
end
it 'load_and_authorize_resource properly passes first argument as the resource name' do
expect(cancan_resource_class = double).to receive(:load_and_authorize_resource)
allow(CanCan::ControllerResource).to receive(:new).with(@controller, :project, { foo: :bar }) do
cancan_resource_class
end
expect(@controller_class)
.to receive(:before_action).with({}) { |_options, &block| block.call(@controller) }
@controller_class.load_and_authorize_resource :project, foo: :bar
end
it 'load_and_authorize_resource with :prepend prepends the before filter' do
expect(@controller_class).to receive(:prepend_before_action).with({})
@controller_class.load_and_authorize_resource foo: :bar, prepend: true
end
it 'authorize_resource setups a before filter which passes call to ControllerResource' do
expect(cancan_resource_class = double).to receive(:authorize_resource)
allow(CanCan::ControllerResource).to receive(:new).with(@controller, nil, { foo: :bar }) { cancan_resource_class }
expect(@controller_class)
.to receive(:before_action).with({ except: :show, if: true }) do |_options, &block|
block.call(@controller)
end
@controller_class.authorize_resource foo: :bar, except: :show, if: true
end
it 'load_resource setups a before filter which passes call to ControllerResource' do
expect(cancan_resource_class = double).to receive(:load_resource)
allow(CanCan::ControllerResource).to receive(:new).with(@controller, nil, { foo: :bar }) { cancan_resource_class }
expect(@controller_class)
.to receive(:before_action).with({ only: %i[show index], unless: false }) do |_options, &block|
block.call(@controller)
end
@controller_class.load_resource foo: :bar, only: %i[show index], unless: false
end
it 'skip_authorization_check setups a before filter which sets @_authorized to true' do
expect(@controller_class)
.to receive(:before_action).with(:filter_options) { |_options, &block| block.call(@controller) }
@controller_class.skip_authorization_check(:filter_options)
expect(@controller.instance_variable_get(:@_authorized)).to be(true)
end
it 'check_authorization triggers AuthorizationNotPerformed in after filter' do
expect(@controller_class)
.to receive(:after_action).with({ only: [:test] }) { |_options, &block| block.call(@controller) }
expect do
@controller_class.check_authorization({ only: [:test] })
end.to raise_error(CanCan::AuthorizationNotPerformed)
end
it 'check_authorization does not trigger AuthorizationNotPerformed when :if is false' do
allow(@controller).to receive(:check_auth?) { false }
allow(@controller_class)
.to receive(:after_action).with({}) { |_options, &block| block.call(@controller) }
expect do
@controller_class.check_authorization(if: :check_auth?)
end.not_to raise_error
end
it 'check_authorization does not trigger AuthorizationNotPerformed when :unless is true' do
allow(@controller).to receive(:engine_controller?) { true }
expect(@controller_class)
.to receive(:after_action).with({}) { |_options, &block| block.call(@controller) }
expect do
@controller_class.check_authorization(unless: :engine_controller?)
end.not_to raise_error
end
it 'check_authorization does not raise error when @_authorized is set' do
@controller.instance_variable_set(:@_authorized, true)
expect(@controller_class)
.to receive(:after_action).with({ only: [:test] }) { |_options, &block| block.call(@controller) }
expect do
@controller_class.check_authorization(only: [:test])
end.not_to raise_error
end
it 'cancan_resource_class is ControllerResource by default' do
expect(@controller.class.cancan_resource_class).to eq(CanCan::ControllerResource)
end
it 'cancan_skipper is an empty hash with :authorize and :load options and remember changes' do
expect(@controller_class.cancan_skipper).to eq(authorize: {}, load: {})
@controller_class.cancan_skipper[:load] = true
expect(@controller_class.cancan_skipper[:load]).to be(true)
end
it 'skip_authorize_resource adds itself to the cancan skipper with given model name and options' do
@controller_class.skip_authorize_resource(:project, only: %i[index show])
expect(@controller_class.cancan_skipper[:authorize][:project]).to eq(only: %i[index show])
@controller_class.skip_authorize_resource(only: %i[index show])
expect(@controller_class.cancan_skipper[:authorize][nil]).to eq(only: %i[index show])
@controller_class.skip_authorize_resource(:article)
expect(@controller_class.cancan_skipper[:authorize][:article]).to eq({})
end
it 'skip_load_resource adds itself to the cancan skipper with given model name and options' do
@controller_class.skip_load_resource(:project, only: %i[index show])
expect(@controller_class.cancan_skipper[:load][:project]).to eq(only: %i[index show])
@controller_class.skip_load_resource(only: %i[index show])
expect(@controller_class.cancan_skipper[:load][nil]).to eq(only: %i[index show])
@controller_class.skip_load_resource(:article)
expect(@controller_class.cancan_skipper[:load][:article]).to eq({})
end
it 'skip_load_and_authorize_resource adds itself to the cancan skipper with given model name and options' do
@controller_class.skip_load_and_authorize_resource(:project, only: %i[index show])
expect(@controller_class.cancan_skipper[:load][:project]).to eq(only: %i[index show])
expect(@controller_class.cancan_skipper[:authorize][:project]).to eq(only: %i[index show])
end
describe 'when inheriting' do
before(:each) do
@super_controller_class = Class.new
@super_controller = @super_controller_class.new
@sub_controller_class = Class.new(@super_controller_class)
@sub_controller = @sub_controller_class.new
allow(@super_controller_class).to receive(:helper_method)
@super_controller_class.send(:include, CanCan::ControllerAdditions)
@super_controller_class.skip_load_and_authorize_resource(only: %i[index show])
end
it 'sub_classes should skip the same behaviors and actions as super_classes' do
expect(@super_controller_class.cancan_skipper[:load][nil]).to eq(only: %i[index show])
expect(@super_controller_class.cancan_skipper[:authorize][nil]).to eq(only: %i[index show])
expect(@sub_controller_class.cancan_skipper[:load][nil]).to eq(only: %i[index show])
expect(@sub_controller_class.cancan_skipper[:authorize][nil]).to eq(only: %i[index show])
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/ability_spec.rb | spec/cancan/ability_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe CanCan::Ability do
before(:each) do
(@ability = double).extend(CanCan::Ability)
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:named_users) do |t|
t.string :first_name
t.string :last_name
end
end
unless defined?(NamedUser)
class NamedUser < ActiveRecord::Base
attribute :role, :string # Virtual only
end
end
end
it 'is able to :read anything' do
@ability.can :read, :all
expect(@ability.can?(:read, String)).to be(true)
expect(@ability.can?(:read, 123)).to be(true)
end
it "does not have permission to do something it doesn't know about" do
expect(@ability.can?(:foodfight, String)).to be(false)
end
it 'passes true to `can?` when non false/nil is returned in block' do
@ability.can :read, Symbol do |sym|
expect(sym).not_to be_nil
'foo'
end
expect(@ability.can?(:read, :some_symbol)).to be(true)
end
it 'passes nil to a block when no instance is passed' do
@ability.can :read, Symbol do |sym|
expect(sym).to be_nil
true
end
expect(@ability.can?(:read, Symbol)).to be(true)
end
it 'passes to previous rule, if block returns false or nil' do
@ability.can :read, Symbol
@ability.can :read, Integer do |i|
i < 5
end
@ability.can :read, Integer do |i|
i > 10
end
expect(@ability.can?(:read, Symbol)).to be(true)
expect(@ability.can?(:read, 11)).to be(true)
expect(@ability.can?(:read, 1)).to be(true)
expect(@ability.can?(:read, 6)).to be(false)
end
it 'overrides earlier rules with later ones (even if a different exact subject)' do
@ability.cannot :read, Numeric
@ability.can :read, Integer
expect(@ability.can?(:read, 6)).to be(true)
end
it 'performs can(_, :all) before other checks when can(_, :all) is defined before' do
@ability.can :manage, :all
@ability.can :edit, String do |_string|
raise 'Performed a check for :edit before the check for :all'
end
expect { @ability.can? :edit, 'a' }.to_not raise_exception
end
it 'performs can(_, :all) before other checks when can(_, :all) is defined after' do
@ability.can :edit, String do |_string|
raise 'Performed a check for :edit before the check for :all'
end
@ability.can :manage, :all
expect { @ability.can? :edit, 'a' }.to_not raise_exception
end
it 'does not pass class with object if :all objects are accepted' do
@ability.can :preview, :all do |object|
expect(object).to eq(123)
@block_called = true
end
@ability.can?(:preview, 123)
expect(@block_called).to be(true)
end
it 'does not call block when only class is passed, only return true' do
@block_called = false
@ability.can :preview, :all do |_object|
@block_called = true
end
expect(@ability.can?(:preview, Hash)).to be(true)
expect(@block_called).to be(false)
end
it 'passes only object for global manage actions' do
@ability.can :manage, String do |object|
expect(object).to eq('foo')
@block_called = true
end
expect(@ability.can?(:stuff, 'foo')).to be(true)
expect(@block_called).to be(true)
end
it 'makes alias for update or destroy actions to modify action' do
@ability.alias_action :update, :destroy, to: :modify
@ability.can :modify, :all
expect(@ability.can?(:update, 123)).to be(true)
expect(@ability.can?(:destroy, 123)).to be(true)
end
it 'allows deeply nested aliased actions' do
@ability.alias_action :increment, to: :sort
@ability.alias_action :sort, to: :modify
@ability.can :modify, :all
expect(@ability.can?(:increment, 123)).to be(true)
end
it 'raises an Error if alias target is an exist action' do
expect { @ability.alias_action :show, to: :show }
.to raise_error(CanCan::Error, "You can't specify target (show) as alias because it is real action name")
end
it 'always calls block with arguments when passing no arguments to can' do
@ability.can do |action, object_class, object|
expect(action).to eq(:foo)
expect(object_class).to eq(123.class)
expect(object).to eq(123)
@block_called = true
end
@ability.can?(:foo, 123)
expect(@block_called).to be(true)
end
it 'allows passing nil as extra arguments' do
@ability.can :to_s, Integer do |integer, arg1, arg2|
expect(integer).to eq(42)
expect(arg1).to eq(nil)
expect(arg2).to eq(:foo)
@block_called = true
end
@ability.can?(:to_s, 42, nil, nil, :foo)
expect(@block_called).to be(true)
end
it 'passes nil to object when comparing class with can check' do
@ability.can do |action, object_class, object|
expect(action).to eq(:foo)
expect(object_class).to eq(Hash)
expect(object).to be_nil
@block_called = true
end
@ability.can?(:foo, Hash)
expect(@block_called).to be(true)
end
it 'automatically makes alias for index and show into read calls' do
@ability.can :read, :all
expect(@ability.can?(:index, 123)).to be(true)
expect(@ability.can?(:show, 123)).to be(true)
end
it 'automatically makes alias for new and edit into create and update respectively' do
@ability.can :create, :all
@ability.can :update, :all
expect(@ability.can?(:new, 123)).to be(true)
expect(@ability.can?(:edit, 123)).to be(true)
end
it 'does not respond to prepare (now using initialize)' do
expect(@ability).to_not respond_to(:prepare)
end
it 'offers cannot? method which is simply invert of can?' do
expect(@ability.cannot?(:tie, String)).to be(true)
end
it 'is able to specify multiple actions and match any' do
@ability.can %i[read update], :all
expect(@ability.can?(:read, 123)).to be(true)
expect(@ability.can?(:update, 123)).to be(true)
expect(@ability.can?(:count, 123)).to be(false)
end
it 'is able to specify multiple classes and match any' do
@ability.can :update, [String, Range]
expect(@ability.can?(:update, 'foo')).to be(true)
expect(@ability.can?(:update, 1..3)).to be(true)
expect(@ability.can?(:update, 123)).to be(false)
end
it 'checks if there is a permission for any of given subjects' do
@ability.can :update, [String, Range]
expect(@ability.can?(:update, any: ['foo', 1..3])).to be(true)
expect(@ability.can?(:update, any: [1..3, 'foo'])).to be(true)
expect(@ability.can?(:update, any: [123, 'foo'])).to be(true)
expect(@ability.can?(:update, any: [123, 1.0])).to be(false)
end
it 'lists all permissions' do
@ability.can :manage, :all
@ability.can :learn, Range
@ability.can :interpret, Symbol, %i[size to_s]
@ability.cannot :read, String
@ability.cannot :read, Hash
@ability.cannot :preview, Array
expected_list = {
can: {
manage: { 'all' => [] },
learn: { 'Range' => [] },
interpret: { 'Symbol' => %i[size to_s] }
},
cannot: {
read: { 'String' => [], 'Hash' => [] },
index: { 'String' => [], 'Hash' => [] },
show: { 'String' => [], 'Hash' => [] },
preview: { 'Array' => [] }
}
}
expect(@ability.permissions).to eq(expected_list)
end
it 'supports custom objects in the rule' do
@ability.can :read, :stats
expect(@ability.can?(:read, :stats)).to be(true)
expect(@ability.can?(:update, :stats)).to be(false)
expect(@ability.can?(:read, :nonstats)).to be(false)
expect(@ability.can?(:read, any: %i[stats nonstats])).to be(true)
expect(@ability.can?(:read, any: %i[nonstats neitherstats])).to be(false)
end
it 'checks ancestors of class' do
@ability.can :read, Numeric
expect(@ability.can?(:read, Integer)).to be(true)
expect(@ability.can?(:read, 1.23)).to be(true)
expect(@ability.can?(:read, 'foo')).to be(false)
expect(@ability.can?(:read, any: [Integer, String])).to be(true)
end
it "supports 'cannot' method to define what user cannot do" do
@ability.can :read, :all
@ability.cannot :read, Integer
expect(@ability.can?(:read, 'foo')).to be(true)
expect(@ability.can?(:read, 123)).to be(false)
expect(@ability.can?(:read, any: %w[foo bar])).to be(true)
expect(@ability.can?(:read, any: [123, 'foo'])).to be(false)
expect(@ability.can?(:read, any: [123, 456])).to be(false)
end
it 'passes to previous rule, if block returns false or nil' do
@ability.can :read, :all
@ability.cannot :read, Integer do |int|
int > 10 ? nil : (int > 5)
end
expect(@ability.can?(:read, 'foo')).to be(true)
expect(@ability.can?(:read, 3)).to be(true)
expect(@ability.can?(:read, 8)).to be(false)
expect(@ability.can?(:read, 123)).to be(true)
expect(@ability.can?(:read, any: [123, 8])).to be(true)
expect(@ability.can?(:read, any: [8, 9])).to be(false)
end
it 'always returns `false` for single cannot definition' do
@ability.cannot :read, Integer do |int|
int > 10 ? nil : (int > 5)
end
expect(@ability.can?(:read, 'foo')).to be(false)
expect(@ability.can?(:read, 3)).to be(false)
expect(@ability.can?(:read, 8)).to be(false)
expect(@ability.can?(:read, 123)).to be(false)
end
it 'passes to previous cannot definition, if block returns false or nil' do
@ability.cannot :read, :all
@ability.can :read, Integer do |int|
int > 10 ? nil : (int > 5)
end
expect(@ability.can?(:read, 'foo')).to be(false)
expect(@ability.can?(:read, 3)).to be(false)
expect(@ability.can?(:read, 10)).to be(true)
expect(@ability.can?(:read, 123)).to be(false)
end
it 'appends aliased actions' do
@ability.alias_action :update, to: :modify
@ability.alias_action :destroy, to: :modify
expect(@ability.aliased_actions[:modify]).to eq(%i[update destroy])
end
it 'clears aliased actions' do
@ability.alias_action :update, to: :modify
@ability.clear_aliased_actions
expect(@ability.aliased_actions[:modify]).to be_nil
end
it 'passes additional arguments to block from can?' do
@ability.can :read, Integer do |int, x|
int > x
end
expect(@ability.can?(:read, 2, 1)).to be(true)
expect(@ability.can?(:read, 2, 3)).to be(false)
expect(@ability.can?(:read, { any: [4, 5] }, 3)).to be(true)
expect(@ability.can?(:read, { any: [2, 3] }, 3)).to be(false)
end
it 'uses conditions as third parameter and determine abilities from it' do
@ability.can :read, Range, begin: 1, end: 3
expect(@ability.can?(:read, 1..3)).to be(true)
expect(@ability.can?(:read, 1..4)).to be(false)
expect(@ability.can?(:read, Range)).to be(true)
expect(@ability.can?(:read, any: [1..3, 1..4])).to be(true)
expect(@ability.can?(:read, any: [1..4, 2..4])).to be(false)
end
it 'allows an array of options in conditions hash' do
@ability.can :read, Range, begin: [1, 3, 5]
expect(@ability.can?(:read, 1..3)).to be(true)
expect(@ability.can?(:read, 2..4)).to be(false)
expect(@ability.can?(:read, 3..5)).to be(true)
expect(@ability.can?(:read, any: [2..4, 3..5])).to be(true)
expect(@ability.can?(:read, any: [2..4, 2..5])).to be(false)
end
it 'allows a range of options in conditions hash' do
@ability.can :read, Range, begin: 1..3
expect(@ability.can?(:read, 1..10)).to be(true)
expect(@ability.can?(:read, 3..30)).to be(true)
expect(@ability.can?(:read, 4..40)).to be(false)
end
it 'allows a range of time in conditions hash' do
@ability.can :read, Range, begin: 1.day.from_now..3.days.from_now
expect(@ability.can?(:read, 1.day.from_now..10.days.from_now)).to be(true)
expect(@ability.can?(:read, 2.days.from_now..20.days.from_now)).to be(true)
expect(@ability.can?(:read, 4.days.from_now..40.days.from_now)).to be(false)
end
it 'allows nested hashes in conditions hash' do
@ability.can :read, Range, begin: { to_i: 5 }
expect(@ability.can?(:read, 5..7)).to be(true)
expect(@ability.can?(:read, 6..8)).to be(false)
end
it "matches any element passed in to nesting if it's an array (for has_many associations)" do
@ability.can :read, Range, to_a: { to_i: 3 }
expect(@ability.can?(:read, 1..5)).to be(true)
expect(@ability.can?(:read, 4..6)).to be(false)
end
it 'accepts a set as a condition value' do
expect(object_with_foo_two = double(foo: 2)).to receive(:foo)
expect(object_with_foo_three = double(foo: 3)).to receive(:foo)
@ability.can :read, Object, foo: [1, 2, 5].to_set
expect(@ability.can?(:read, object_with_foo_two)).to be(true)
expect(@ability.can?(:read, object_with_foo_three)).to be(false)
end
it 'does not match subjects return nil for methods that must match nested a nested conditions hash' do
expect(object_with_foo = double(foo: :bar)).to receive(:foo)
@ability.can :read, Array, first: { foo: :bar }
expect(@ability.can?(:read, [object_with_foo])).to be(true)
expect(@ability.can?(:read, [])).to be(false)
end
it 'matches strings but not substrings specified in a conditions hash' do
@ability.can :read, String, presence: 'declassified'
expect(@ability.can?(:read, 'declassified')).to be(true)
expect(@ability.can?(:read, 'classified')).to be(false)
end
it 'does not stop at cannot definition when comparing class' do
@ability.can :read, Range
@ability.cannot :read, Range, begin: 1
expect(@ability.can?(:read, 2..5)).to be(true)
expect(@ability.can?(:read, 1..5)).to be(false)
expect(@ability.can?(:read, Range)).to be(true)
end
it 'does not stop at cannot with block when comparing class' do
@ability.can :read, Integer
@ability.cannot(:read, Integer) { |int| int > 5 }
expect(@ability.can?(:read, 123)).to be(false)
expect(@ability.can?(:read, Integer)).to be(true)
end
it 'stops at cannot definition when no hash is present' do
@ability.can :read, :all
@ability.cannot :read, Range
expect(@ability.can?(:read, 1..5)).to be(false)
expect(@ability.can?(:read, Range)).to be(false)
end
it 'allows to check ability for Module' do
module B
end
class A
include B
end
@ability.can :read, B
expect(@ability.can?(:read, A)).to be(true)
expect(@ability.can?(:read, A.new)).to be(true)
end
it 'passes nil to a block for ability on Module when no instance is passed' do
module B
end
class A
include B
end
@ability.can :read, B do |sym|
expect(sym).to be_nil
true
end
expect(@ability.can?(:read, B)).to be(true)
expect(@ability.can?(:read, A)).to be(true)
end
it 'checks permissions through association when passing a hash of subjects' do
@ability.can :read, Range, string: { length: 3 }
expect(@ability.can?(:read, 'foo' => Range)).to be(true)
expect(@ability.can?(:read, 'foobar' => Range)).to be(false)
expect(@ability.can?(:read, 123 => Range)).to be(true)
expect(@ability.can?(:read, any: [{ 'foo' => Range }, { 'foobar' => Range }])).to be(true)
expect(@ability.can?(:read, any: [{ 'food' => Range }, { 'foobar' => Range }])).to be(false)
end
it 'checks permissions correctly when passing a hash of subjects with multiple definitions' do
@ability.can :read, Range, string: { length: 4 }
@ability.can %i[create read], Range, string: { upcase: 'FOO' }
expect(@ability.can?(:read, 'foo' => Range)).to be(true)
expect(@ability.can?(:read, 'foobar' => Range)).to be(false)
expect(@ability.can?(:read, 1234 => Range)).to be(true)
expect(@ability.can?(:read, any: [{ 'foo' => Range }, { 'foobar' => Range }])).to be(true)
expect(@ability.can?(:read, any: [{ 'foo.bar' => Range }, { 'foobar' => Range }])).to be(false)
end
it 'allows to check ability on Hash-like object' do
class Container < Hash
end
@ability.can :read, Container
expect(@ability.can?(:read, Container.new)).to be(true)
end
it "has initial values based on hash conditions of 'new' action" do
@ability.can :manage, Range, foo: 'foo', hash: { skip: 'hashes' }
@ability.can :create, Range, bar: 123, array: %w[skip arrays]
@ability.can :new, Range, baz: 'baz', range: 1..3
@ability.cannot :new, Range, ignore: 'me'
expect(@ability.attributes_for(:new, Range)).to eq(foo: 'foo', bar: 123, baz: 'baz')
end
it 'allows to check ability even the object implements `#to_a`' do
stub_const('X', Class.new do
def self.to_a
[]
end
end)
@ability.can :read, X
expect(@ability.can?(:read, X.new)).to be(true)
end
it 'respects `#to_ary`' do
stub_const('X', Class.new do
def self.to_ary
[Y]
end
end)
stub_const('Y', Class.new)
@ability.can :read, X
expect(@ability.can?(:read, X.new)).to be(false)
expect(@ability.can?(:read, Y.new)).to be(true)
end
# rubocop:disable Style/SymbolProc
describe 'different usages of blocks and procs' do
class A
def active?
true
end
end
it 'can use a do...end block' do
@ability.can :read, A do |a|
a.active?
end
expect(@ability).to be_able_to(:read, A.new)
end
it 'can use a inline block' do
@ability.can(:read, A) { |a| a.active? }
expect(@ability).to be_able_to(:read, A.new)
end
it 'can use a method reference' do
@ability.can :read, A, &:active?
expect(@ability).to be_able_to(:read, A.new)
end
it 'can use a Proc' do
proc = Proc.new(&:active?)
@ability.can :read, A, &proc
expect(@ability).to be_able_to(:read, A.new)
end
end
# rubocop:enable Style/SymbolProc
describe '#authorize!' do
describe 'when ability is not authorized to perform an action' do
it 'raises access denied exception' do
begin
@ability.authorize! :read, :foo, 1, 2, 3, message: 'Access denied!'
rescue CanCan::AccessDenied => e
expect(e.message).to eq('Access denied!')
expect(e.action).to eq(:read)
expect(e.subject).to eq(:foo)
expect(e.conditions).to eq([1, 2, 3])
else
raise 'Expected CanCan::AccessDenied exception to be raised'
end
end
describe 'when no extra conditions are specified' do
it 'raises access denied exception without conditions' do
begin
@ability.authorize! :read, :foo, message: 'Access denied!'
rescue CanCan::AccessDenied => e
expect(e.conditions).to eq([])
else
raise 'Expected CanCan::AccessDenied exception to be raised'
end
end
end
describe 'when no message is specified' do
it 'raises access denied exception with default message' do
begin
@ability.authorize! :read, :foo
rescue CanCan::AccessDenied => e
e.default_message = 'Access denied!'
expect(e.message).to eq('Access denied!')
else
raise 'Expected CanCan::AccessDenied exception to be raised'
end
end
end
end
describe 'when ability is authorized to perform an action' do
it 'does not raise access denied exception' do
@ability.can :read, :foo
expect do
expect(@ability.authorize!(:read, :foo)).to eq(:foo)
end.to_not raise_error
end
end
end
it 'knows when block is used in conditions' do
@ability.can :read, :foo
expect(@ability).to_not have_block(:read, :foo)
@ability.can :read, :foo do |_foo|
false
end
expect(@ability).to have_block(:read, :foo)
end
it 'knows when raw sql is used in conditions' do
@ability.can :read, :foo
expect(@ability).to_not have_raw_sql(:read, :foo)
@ability.can :read, :foo, 'false'
expect(@ability).to have_raw_sql(:read, :foo)
end
it 'determines model adapter class by asking AbstractAdapter' do
adapter_class = double
model_class = double
allow(CanCan::ModelAdapters::AbstractAdapter).to receive(:adapter_class).with(model_class) { adapter_class }
allow(adapter_class).to receive(:new).with(model_class, []) { :adapter_instance }
expect(@ability.model_adapter(model_class, :read)).to eq(:adapter_instance)
end
it "raises an error when attempting to use a block with a hash condition since it's not likely what they want" do
expect do
@ability.can :read, Array, published: true do
false
end
end.to raise_error(CanCan::BlockAndConditionsError)
end
it 'allows attribute-level rules' do
@ability.can :read, Array, :to_s
expect(@ability.can?(:read, Array, :to_s)).to be(true)
expect(@ability.can?(:read, Array, :size)).to be(false)
expect(@ability.can?(:read, Array)).to be(true)
end
it 'allows an array of attributes in rules' do
@ability.can :read, [Array, String], %i[to_s size]
expect(@ability.can?(:read, String, :size)).to be(true)
expect(@ability.can?(:read, Array, :to_s)).to be(true)
end
it 'allows cannot of rules with attributes' do
@ability.can :read, Array
@ability.cannot :read, Array, :to_s
expect(@ability.can?(:read, Array, :to_s)).to be(false)
expect(@ability.can?(:read, Array)).to be(true)
expect(@ability.can?(:read, Array, :size)).to be(true)
end
it 'has precedence with attribute-level rules' do
@ability.cannot :read, Array
@ability.can :read, Array, :to_s
expect(@ability.can?(:read, Array, :to_s)).to be(true)
expect(@ability.can?(:read, Array, :size)).to be(false)
expect(@ability.can?(:read, Array)).to be(true)
end
it 'allows permission on all attributes when none are given' do
@ability.can :update, Object
expect(@ability.can?(:update, Object, :password)).to be(true)
end
it 'allows strings when checking attributes' do
@ability.can :update, Object, :name
expect(@ability.can?(:update, Object, 'name')).to be(true)
end
it 'passes attribute to block; nil if no attribute given' do
@ability.can :update, Range do |_range, attribute|
attribute == :name
end
expect(@ability.can?(:update, 1..3, :name)).to be(true)
expect(@ability.can?(:update, 2..4)).to be(false)
end
it 'combines attribute checks with conditions hash' do
@ability.can :update, Range, begin: 1
@ability.can :update, Range, :name, begin: 2
expect(@ability.can?(:update, 1..3, :notname)).to be(true)
expect(@ability.can?(:update, 2..4, :notname)).to be(false)
expect(@ability.can?(:update, 2..4, :name)).to be(true)
expect(@ability.can?(:update, 3..5, :name)).to be(false)
expect(@ability.can?(:update, Range)).to be(true)
expect(@ability.can?(:update, Range, :name)).to be(true)
end
it 'returns an array of permitted attributes for a given action and subject' do
@ability.can :read, NamedUser
@ability.can :read, Array, :special
@ability.can :action, :subject, :attribute
expect(@ability.permitted_attributes(:read, NamedUser)).to eq(%i[id first_name last_name role])
expect(@ability.permitted_attributes(:read, Array)).to eq([:special])
expect(@ability.permitted_attributes(:action, :subject)).to eq([:attribute])
end
it 'returns permitted attributes when used with blocks' do
user_class = Struct.new(:first_name, :last_name)
@ability.can :read, user_class, %i[first_name last_name]
@ability.cannot(:read, user_class, :first_name) { |u| u.last_name == 'Smith' }
expect(@ability.permitted_attributes(:read, user_class.new('John', 'Jones'))).to eq(%i[first_name last_name])
expect(@ability.permitted_attributes(:read, user_class.new('John', 'Smith'))).to eq(%i[last_name])
end
it 'returns permitted attributes when using conditions' do
@ability.can :read, Range, %i[nil? to_s class]
@ability.cannot :read, Range, %i[nil? to_s], begin: 2
@ability.can :read, Range, :to_s, end: 4
expect(@ability.permitted_attributes(:read, 1..3)).to eq(%i[nil? to_s class])
expect(@ability.permitted_attributes(:read, 2..5)).to eq([:class])
expect(@ability.permitted_attributes(:read, 2..4)).to eq(%i[class to_s])
end
it 'respects inheritance when checking permitted attributes' do
@ability.can :read, Integer, %i[nil? to_s class]
@ability.cannot :read, Numeric, %i[nil? class]
expect(@ability.permitted_attributes(:read, Integer)).to eq([:to_s])
end
it 'does not retain references to subjects that do not have direct rules' do
@ability.can :read, String
@ability.can?(:read, 'foo')
expect(@ability.instance_variable_get(:@rules_index)).not_to have_key('foo')
end
describe 'unauthorized message' do
after(:each) do
I18n.backend = nil
end
it 'uses action/subject in i18n' do
I18n.backend.store_translations :en, unauthorized: { update: { array: 'foo' } }
expect(@ability.unauthorized_message(:update, Array)).to eq('foo')
expect(@ability.unauthorized_message(:update, [1, 2, 3])).to eq('foo')
expect(@ability.unauthorized_message(:update, :missing)).to be_nil
end
it "uses model's name in i18n" do
class Account
include ActiveModel::Model
end
I18n.backend.store_translations :en,
activemodel: { models: { account: 'english name' } },
unauthorized: { update: { all: '%{subject}' } }
I18n.backend.store_translations :ja,
activemodel: { models: { account: 'japanese name' } },
unauthorized: { update: { all: '%{subject}' } }
I18n.with_locale(:en) do
expect(@ability.unauthorized_message(:update, Account)).to eq('english name')
end
I18n.with_locale(:ja) do
expect(@ability.unauthorized_message(:update, Account)).to eq('japanese name')
end
end
it "uses action's name in i18n" do
class Account
include ActiveModel::Model
end
I18n.backend.store_translations :en,
actions: { update: 'english name' },
unauthorized: { update: { all: '%{action}' } }
I18n.backend.store_translations :ja,
actions: { update: 'japanese name' },
unauthorized: { update: { all: '%{action}' } }
I18n.with_locale(:en) do
expect(@ability.unauthorized_message(:update, Account)).to eq('english name')
end
I18n.with_locale(:ja) do
expect(@ability.unauthorized_message(:update, Account)).to eq('japanese name')
end
end
it 'uses symbol as subject directly' do
I18n.backend.store_translations :en, unauthorized: { has: { cheezburger: 'Nom nom nom. I eated it.' } }
expect(@ability.unauthorized_message(:has, :cheezburger)).to eq('Nom nom nom. I eated it.')
end
it 'uses correct i18n keys when hashes are used' do
# Hashes are sent as subject when using:
# load_and_authorize_resource :blog
# load_and_authorize_resource through: :blog
# And subject for collection actions (ie: index) returns: { <Blog id:1> => Post(id:integer) }
I18n.backend.store_translations :en, unauthorized: { update: { all: 'all', array: 'foo' } }
expect(@ability.unauthorized_message(:update, Hash => Array)).to eq('foo')
end
it 'uses correct subject when hashes are used' do
I18n.backend.store_translations :en, unauthorized: { manage: { all: '%<action>s %<subject>s' } }
expect(@ability.unauthorized_message(:update, Hash => Array)).to eq('update array')
end
it "falls back to 'manage' and 'all'" do
I18n.backend.store_translations :en, unauthorized: {
manage: { all: 'manage all', array: 'manage array' },
update: { all: 'update all', array: 'update array' }
}
expect(@ability.unauthorized_message(:update, Array)).to eq('update array')
expect(@ability.unauthorized_message(:update, Hash)).to eq('update all')
expect(@ability.unauthorized_message(:foo, Array)).to eq('manage array')
expect(@ability.unauthorized_message(:foo, Hash)).to eq('manage all')
end
it 'follows aliased actions' do
I18n.backend.store_translations :en, unauthorized: { modify: { array: 'modify array' } }
@ability.alias_action :update, to: :modify
expect(@ability.unauthorized_message(:update, Array)).to eq('modify array')
expect(@ability.unauthorized_message(:edit, Array)).to eq('modify array')
end
it 'has variables for action and subject' do
# old syntax for now in case testing with old I18n
I18n.backend.store_translations :en, unauthorized: { manage: { all: '%<action>s %<subject>s' } }
expect(@ability.unauthorized_message(:update, Array)).to eq('update array')
expect(@ability.unauthorized_message(:update, ArgumentError)).to eq('update argument error')
expect(@ability.unauthorized_message(:edit, 1..3)).to eq('edit range')
end
end
describe '#merge' do
it 'adds the rules from the given ability' do
@ability.can :use, :tools
(another_ability = double).extend(CanCan::Ability)
another_ability.can :use, :search
@ability.merge(another_ability)
expect(@ability.can?(:use, :search)).to be(true)
expect(@ability.send(:rules).size).to eq(2)
end
it 'adds the aliased actions from the given ability' do
@ability.alias_action :show, to: :see
(another_ability = double).extend(CanCan::Ability)
another_ability.alias_action :create, :update, to: :manage
@ability.merge(another_ability)
expect(@ability.aliased_actions).to eq(
read: %i[index show],
create: %i[new],
update: %i[edit],
manage: %i[create update],
see: %i[show]
)
end
it 'overwrittes the aliased actions with the value from the given ability' do
@ability.alias_action :show, :index, to: :see
(another_ability = double).extend(CanCan::Ability)
another_ability.alias_action :show, to: :see
@ability.merge(another_ability)
expect(@ability.aliased_actions).to eq(
read: %i[index show],
create: %i[new],
update: %i[edit],
see: %i[show]
)
end
it 'can add an empty ability' do
(another_ability = double).extend(CanCan::Ability)
@ability.merge(another_ability)
expect(@ability.send(:rules).size).to eq(0)
end
end
describe 'when #can? is used with a Hash (nested resources)' do
it 'is unauthorized with no rules' do
expect(@ability.can?(:read, 1 => Symbol)).to be(false)
end
it 'is authorized when the child is authorized' do
@ability.can :read, Symbol
expect(@ability.can?(:read, 1 => Symbol)).to be(true)
end
it 'is authorized when the condition doesn\'t concern the parent' do
@ability.can :read, Symbol, whatever: true
expect(@ability.can?(:read, 1 => Symbol)).to be(true)
end
it 'verifies the parent against an equality condition' do
@ability.can :read, Symbol, integer: 1
expect(@ability.can?(:read, 1 => Symbol)).to be(true)
expect(@ability.can?(:read, 2 => Symbol)).to be(false)
end
it 'verifies the parent against an array condition' do
@ability.can :read, Symbol, integer: [0, 1]
expect(@ability.can?(:read, 1 => Symbol)).to be(true)
expect(@ability.can?(:read, 2 => Symbol)).to be(false)
end
it 'verifies the parent against a hash condition' do
@ability.can :read, Symbol, integer: { to_i: 1 }
expect(@ability.can?(:read, 1 => Symbol)).to be(true)
expect(@ability.can?(:read, 2 => Symbol)).to be(false)
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/rule_compressor_spec.rb | spec/cancan/rule_compressor_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe CanCan::RulesCompressor do
before do
class Blog
end
end
def can(action, subject, args = nil)
CanCan::Rule.new(true, action, subject, args, nil)
end
def cannot(action, subject, args = nil)
CanCan::Rule.new(false, action, subject, args, nil)
end
context 'a "cannot catch_all" rule is in first position' do
let(:rules) do
[cannot(:read, Blog),
can(:read, Blog)]
end
it 'deletes it' do
expect(described_class.new(rules).rules_collapsed).to eq rules[1..-1]
end
end
context 'a "can catch all" rule is in last position' do
let(:rules) do
[cannot(:read, Blog, id: 2),
can(:read, Blog, id: 1),
can(:read, Blog)]
end
it 'deletes all previous rules' do
expect(described_class.new(rules).rules_collapsed).to eq [rules.last]
end
end
context 'a "can catch_all" rule is in front of others can rules' do
let(:rules) do
[can(:read, Blog, id: 1),
can(:read, Blog),
can(:read, Blog, id: 3),
can(:read, Blog, author: { id: 3 }),
cannot(:read, Blog, private: true)]
end
it 'deletes all previous rules and subsequent rules of the same type' do
expect(described_class.new(rules).rules_collapsed).to eq [rules[1], rules.last]
end
end
context 'a "cannot catch_all" rule is in front of others cannot rules' do
let(:rules) do
[can(:read, Blog, id: 1),
can(:read, Blog),
can(:read, Blog, id: 3),
cannot(:read, Blog),
cannot(:read, Blog, private: true),
can(:read, Blog, id: 3)]
end
it 'deletes all previous rules and subsequent rules of the same type' do
expect(described_class.new(rules).rules_collapsed).to eq [rules.last]
end
end
context 'a lot of rules' do
let(:rules) do
[
cannot(:read, Blog, id: 4),
can(:read, Blog, id: 1),
can(:read, Blog),
can(:read, Blog, id: 3),
cannot(:read, Blog),
cannot(:read, Blog, private: true),
can(:read, Blog, id: 3),
can(:read, Blog, id: 8),
cannot(:read, Blog, id: 5)
]
end
it 'minimizes the rules' do
expect(described_class.new(rules).rules_collapsed).to eq rules.last(3)
end
end
context 'duplicate rules' do
let(:rules) do
[can(:read, Blog, id: 4),
can(:read, Blog, id: 1),
can(:read, Blog, id: 2),
can(:read, Blog, id: 2),
can(:read, Blog, id: 3),
can(:read, Blog, id: 2)]
end
it 'minimizes the rules, by removing duplicates' do
expect(described_class.new(rules).rules_collapsed).to eq [rules[0], rules[1], rules[4], rules[5]]
end
end
context 'duplicates rules with cannot' do
let(:rules) do
[can(:read, Blog, id: 1),
cannot(:read, Blog, id: 1)]
end
it 'minimizes the rules, by removing useless previous rules' do
expect(described_class.new(rules).rules_collapsed).to eq [rules[1]]
end
end
context 'duplicates rules with cannot and can again' do
let(:rules) do
[can(:read, Blog, id: [1, 2]),
cannot(:read, Blog, id: 1),
can(:read, Blog, id: 1)]
end
it 'minimizes the rules, by removing useless previous rules' do
expect(described_class.new(rules).rules_collapsed).to eq [rules[0], rules[2]]
end
end
context 'duplicates rules with 2 cannot' do
let(:rules) do
[can(:read, Blog),
cannot(:read, Blog, id: 1),
cannot(:read, Blog, id: 1)]
end
it 'minimizes the rules, by removing useless previous rules' do
expect(described_class.new(rules).rules_collapsed).to eq [rules[0], rules[2]]
end
end
# TODO: not supported yet
xcontext 'merges rules' do
let(:rules) do
[can(:read, Blog, id: 4),
can(:read, Blog, id: 1),
can(:read, Blog, id: 2),
can(:read, Blog, id: 2),
can(:read, Blog, id: 3),
can(:read, Blog, id: 2)]
end
it 'minimizes the rules, by merging them' do
expect(described_class.new(rules).rules_collapsed).to eq [can(:read, Blog, id: [4, 1, 2, 3])]
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/matchers_spec.rb | spec/cancan/matchers_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe 'be_able_to' do
subject { double }
context 'check single ability' do
it 'delegates to can?' do
is_expected.to receive(:can?).with(:read, 123) { true }
is_expected.to be_able_to(:read, 123)
end
it 'reports a nice failure message for should' do
is_expected.to receive(:can?).with(:read, 123) { false }
expect do
is_expected.to be_able_to(:read, 123)
end.to raise_error('expected to be able to :read 123')
end
it 'reports a nice failure message for should not' do
is_expected.to receive(:can?).with(:read, 123) { true }
expect do
is_expected.to_not be_able_to(:read, 123)
end.to raise_error('expected not to be able to :read 123')
end
it 'delegates additional arguments to can? and reports in failure message' do
is_expected.to receive(:can?).with(:read, 123, 456) { false }
expect do
is_expected.to be_able_to(:read, 123, 456)
end.to raise_error('expected to be able to :read 123 456')
end
end
context 'check array of abilities' do
it 'delegates to can? with array of abilities with one action' do
is_expected.to receive(:can?).with(:read, 123) { true }
is_expected.to be_able_to([:read], 123)
end
it 'delegates to can? with array of abilities with multiple actions' do
is_expected.to receive(:can?).with(:read, 123) { true }
is_expected.to receive(:can?).with(:update, 123) { true }
is_expected.to be_able_to(%i[read update], 123)
end
it 'delegates to can? with array of abilities with empty array' do
is_expected.not_to be_able_to([], 123)
end
it 'delegates to can? with array of abilities with only one eligible ability' do
is_expected.to receive(:can?).with(:read, 123) { true }
is_expected.to receive(:can?).with(:update, 123) { false }
is_expected.not_to be_able_to(%i[read update], 123)
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/accessible_by_has_many_through_spec.rb | spec/cancan/model_adapters/accessible_by_has_many_through_spec.rb | require 'spec_helper'
# integration tests for latest ActiveRecord version.
RSpec.describe CanCan::ModelAdapters::ActiveRecord5Adapter do
let(:ability) { double.extend(CanCan::Ability) }
let(:users_table) { Post.table_name }
let(:posts_table) { Post.table_name }
let(:likes_table) { Like.table_name }
before :each do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:users) do |t|
t.string :name
t.timestamps null: false
end
create_table(:posts) do |t|
t.string :title
t.boolean :published, default: true
t.integer :user_id
t.timestamps null: false
end
create_table(:likes) do |t|
t.integer :post_id
t.integer :user_id
t.timestamps null: false
end
create_table(:editors) do |t|
t.integer :post_id
t.integer :user_id
t.timestamps null: false
end
end
class User < ActiveRecord::Base
has_many :posts
has_many :likes
has_many :editors
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :likes
has_many :editors
end
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Editor < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
end
before do
@user1 = User.create!
@user2 = User.create!
@post1 = Post.create!(title: 'post1', user: @user1)
@post2 = Post.create!(user: @user1, published: false)
@post3 = Post.create!(user: @user2)
@like1 = Like.create!(post: @post1, user: @user1)
@like2 = Like.create!(post: @post1, user: @user2)
@editor1 = Editor.create(user: @user1, post: @post2)
ability.can :read, Post, user_id: @user1
ability.can :read, Post, editors: { user_id: @user1 }
end
CanCan.valid_accessible_by_strategies.each do |strategy|
context "using #{strategy} strategy" do
before :each do
CanCan.accessible_by_strategy = strategy
end
describe 'preloading of associations' do
it 'preloads associations correctly' do
posts = Post.accessible_by(ability).where(published: true).includes(likes: :user)
expect(posts[0].association(:likes)).to be_loaded
expect(posts[0].likes[0].association(:user)).to be_loaded
end
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
describe 'selecting custom columns' do
it 'extracts custom columns correctly' do
posts = Post.accessible_by(ability).where(published: true).select('posts.title as mytitle')
expect(posts[0].mytitle).to eq 'post1'
end
end
end
describe 'filtering of results' do
it 'adds the where clause correctly' do
posts = Post.accessible_by(ability).where(published: true)
expect(posts.length).to eq 1
end
end
end
end
unless CanCan::ModelAdapters::ActiveRecordAdapter.version_lower?('5.0.0')
describe 'filtering of results - subquery' do
before :each do
CanCan.accessible_by_strategy = :subquery
end
it 'adds the where clause correctly with joins' do
posts = Post.joins(:editors).where('editors.user_id': @user1.id).accessible_by(ability)
expect(posts.length).to eq 1
end
end
end
describe 'filtering of results - left_joins' do
before :each do
CanCan.accessible_by_strategy = :left_join
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.2.0')
it 'adds the where clause correctly with joins on AR 5.2+' do
posts = Post.joins(:editors).where('editors.user_id': @user1.id).accessible_by(ability)
expect(posts.length).to eq 1
end
end
it 'adds the where clause correctly without joins' do
posts = Post.where('editors.user_id': @user1.id).accessible_by(ability)
expect(posts.length).to eq 1
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/conditions_extractor_spec.rb | spec/cancan/model_adapters/conditions_extractor_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe CanCan::ModelAdapters::ConditionsExtractor do
before do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:categories) do |t|
t.string :name
t.boolean :visible
t.timestamps null: false
end
create_table(:projects) do |t|
t.string :name
t.timestamps null: false
end
create_table(:articles) do |t|
t.string :name
t.timestamps null: false
t.boolean :published
t.boolean :secret
t.integer :priority
t.integer :category_id
t.integer :user_id
end
create_table(:comments) do |t|
t.boolean :spam
t.integer :article_id
t.timestamps null: false
end
create_table(:legacy_mentions) do |t|
t.integer :user_id
t.integer :article_id
t.timestamps null: false
end
create_table(:users) do |t|
t.timestamps null: false
end
create_table(:transactions) do |t|
t.integer :sender_id
t.integer :receiver_id
t.integer :supervisor_id
end
end
class Project < ActiveRecord::Base
end
class Category < ActiveRecord::Base
has_many :articles
end
class Article < ActiveRecord::Base
belongs_to :category
has_many :comments
has_many :mentions
has_many :mentioned_users, through: :mentions, source: :user
belongs_to :user
end
class Mention < ActiveRecord::Base
self.table_name = 'legacy_mentions'
belongs_to :user
belongs_to :article
end
class Comment < ActiveRecord::Base
belongs_to :article
end
class User < ActiveRecord::Base
has_many :articles
has_many :mentions
has_many :mentioned_articles, through: :mentions, source: :article
end
class Transaction < ActiveRecord::Base
belongs_to :sender, class_name: 'User', foreign_key: :sender_id
belongs_to :receiver, class_name: 'User', foreign_key: :receiver_id
belongs_to :supervisor, class_name: 'User', foreign_key: :supervisor_id
end
end
describe 'converts hash of conditions into database sql where format' do
it 'converts a simple association' do
conditions = described_class.new(User).tableize_conditions(articles: { id: 1 })
expect(conditions).to eq(articles: { id: 1 })
end
it 'converts a nested association' do
conditions = described_class.new(User).tableize_conditions(articles: { category: { id: 1 } })
expect(conditions).to eq(categories: { id: 1 })
end
it 'converts two associations' do
conditions = described_class.new(User).tableize_conditions(articles: { id: 2, category: { id: 1 } })
expect(conditions).to eq(articles: { id: 2 }, categories: { id: 1 })
end
it 'converts has_many through' do
conditions = described_class.new(Article).tableize_conditions(mentioned_users: { id: 1 })
expect(conditions).to eq(users: { id: 1 })
end
it 'converts associations named differently from the table' do
conditions = described_class.new(Transaction).tableize_conditions(sender: { id: 1 })
expect(conditions).to eq(users: { id: 1 })
end
it 'converts associations properly when the same table is referenced twice' do
conditions = described_class.new(Transaction).tableize_conditions(sender: { id: 1 }, receiver: { id: 2 })
expect(conditions).to eq(users: { id: 1 }, receivers_transactions: { id: 2 })
end
it 'converts very complex nested sets' do
original_conditions = { user: { id: 1 },
mentioned_users: { name: 'a name',
mentioned_articles: { id: 2 },
articles: { user: { name: 'deep' },
mentioned_users: { name: 'd2' } } } }
conditions = described_class.new(Article).tableize_conditions(original_conditions)
expect(conditions).to eq(users: { id: 1 },
mentioned_articles_users: { id: 2 },
mentioned_users_articles: { name: 'a name' },
users_articles: { name: 'deep' },
mentioned_users_articles_2: { name: 'd2' })
end
it 'converts complex nested sets with duplicates' do
original_conditions = { sender: { id: 'sender', articles: { id: 'article1' } },
receiver: { id: 'receiver', articles: { id: 'article2' } } }
conditions = described_class.new(Transaction).tableize_conditions(original_conditions)
expect(conditions).to eq(users: { id: 'sender' },
articles: { id: 'article1' },
receivers_transactions: { id: 'receiver' },
articles_users: { id: 'article2' })
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/active_record_adapter_spec.rb | spec/cancan/model_adapters/active_record_adapter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe CanCan::ModelAdapters::ActiveRecordAdapter do
let(:true_v) do
ActiveRecord::Base.connection.quoted_true
end
let(:false_v) do
ActiveRecord::Base.connection.quoted_false
end
let(:false_condition) { "#{true_v}=#{false_v}" }
before :each do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:categories) do |t|
t.string :name
t.boolean :visible
t.timestamps null: false
end
create_table(:projects) do |t|
t.string :name
t.timestamps null: false
end
create_table(:companies) do |t|
t.boolean :admin
end
create_table(:articles) do |t|
t.string :name
t.timestamps null: false
t.boolean :published
t.boolean :secret
t.integer :priority
t.integer :category_id
t.integer :project_id
t.integer :user_id
end
create_table(:comments) do |t|
t.boolean :spam
t.integer :article_id
t.integer :project_id
t.timestamps null: false
end
create_table(:legacy_comments) do |t|
t.integer :post_id
t.timestamps null: false
end
create_table(:legacy_mentions) do |t|
t.integer :user_id
t.integer :article_id
t.timestamps null: false
end
create_table(:attachments) do |t|
t.integer :attachable_id
t.string :attachable_type
t.timestamps null: false
end
create_table(:users) do |t|
t.string :name
t.timestamps null: false
end
end
class Project < ActiveRecord::Base
has_many :articles
has_many :comments
end
class Category < ActiveRecord::Base
has_many :articles
end
class Company < ActiveRecord::Base
end
class Article < ActiveRecord::Base
belongs_to :category
belongs_to :company
has_many :comments
has_many :mentions
has_many :mentioned_users, through: :mentions, source: :user
belongs_to :user
belongs_to :project
has_many :attachments, as: :attachable
scope :unpopular, lambda {
joins('LEFT OUTER JOIN comments ON (comments.post_id = posts.id)')
.group('articles.id')
.where('COUNT(comments.id) < 3')
}
end
class Mention < ActiveRecord::Base
self.table_name = 'legacy_mentions'
belongs_to :user
belongs_to :article
end
class Comment < ActiveRecord::Base
belongs_to :article
belongs_to :project
has_many :attachments, as: :attachable
end
class LegacyComment < ActiveRecord::Base
belongs_to :article, foreign_key: 'post_id'
belongs_to :project
end
class Attachment < ActiveRecord::Base
belongs_to :attachable, polymorphic: true
end
class User < ActiveRecord::Base
has_many :articles
has_many :mentions
has_many :mentioned_articles, through: :mentions, source: :article
has_many :comments, through: :articles
end
(@ability = double).extend(CanCan::Ability)
@article_table = Article.table_name
@comment_table = Comment.table_name
end
CanCan.valid_accessible_by_strategies.each do |strategy|
context "base functionality with #{strategy} strategy" do
before :each do
CanCan.accessible_by_strategy = strategy
end
it 'does not fires query with accessible_by() for abilities defined with association' do
user = User.create!
@ability.can :edit, Article, user.articles.unpopular
callback = ->(*) { raise 'No query expected' }
ActiveSupport::Notifications.subscribed(callback, 'sql.active_record') do
Article.accessible_by(@ability, :edit)
nil
end
end
it 'fetches only the articles that are published' do
@ability.can :read, Article, published: true
article1 = Article.create!(published: true)
Article.create!(published: false)
expect(Article.accessible_by(@ability)).to eq([article1])
end
it 'is for only active record classes' do
if ActiveRecord.version > Gem::Version.new('5')
expect(CanCan::ModelAdapters::ActiveRecord5Adapter).to_not be_for_class(Object)
expect(CanCan::ModelAdapters::ActiveRecord5Adapter).to be_for_class(Article)
expect(CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article))
.to eq(CanCan::ModelAdapters::ActiveRecord5Adapter)
elsif ActiveRecord.version > Gem::Version.new('4')
expect(CanCan::ModelAdapters::ActiveRecord4Adapter).to_not be_for_class(Object)
expect(CanCan::ModelAdapters::ActiveRecord4Adapter).to be_for_class(Article)
expect(CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article))
.to eq(CanCan::ModelAdapters::ActiveRecord4Adapter)
end
end
it 'finds record' do
article = Article.create!
adapter = CanCan::ModelAdapters::AbstractAdapter.adapter_class(Article)
expect(adapter.find(Article, article.id)).to eq(article)
end
it 'does not fetch any records when no abilities are defined' do
Article.create!
expect(Article.accessible_by(@ability)).to be_empty
end
it 'fetches all articles when one can read all' do
@ability.can :read, Article
article = Article.create!
expect(Article.accessible_by(@ability)).to match_array([article])
end
it 'fetches only the articles that are published' do
@ability.can :read, Article, published: true
article1 = Article.create!(published: true)
Article.create!(published: false)
expect(Article.accessible_by(@ability)).to match_array([article1])
end
it 'fetches any articles which are published or secret' do
@ability.can :read, Article, published: true
@ability.can :read, Article, secret: true
article1 = Article.create!(published: true, secret: false)
article2 = Article.create!(published: true, secret: true)
article3 = Article.create!(published: false, secret: true)
Article.create!(published: false, secret: false)
expect(Article.accessible_by(@ability)).to match_array([article1, article2, article3])
end
it 'fetches any articles which we are cited in' do
user = User.create!
cited = Article.create!
Article.create!
cited.mentioned_users << user
@ability.can :read, Article, mentioned_users: { id: user.id }
@ability.can :read, Article, mentions: { user_id: user.id }
expect(Article.accessible_by(@ability)).to match_array([cited])
end
it 'fetches only the articles that are published and not secret' do
@ability.can :read, Article, published: true
@ability.cannot :read, Article, secret: true
article1 = Article.create!(published: true, secret: false)
Article.create!(published: true, secret: true)
Article.create!(published: false, secret: true)
Article.create!(published: false, secret: false)
expect(Article.accessible_by(@ability)).to match_array([article1])
end
it 'only reads comments for articles which are published' do
@ability.can :read, Comment, article: { published: true }
comment1 = Comment.create!(article: Article.create!(published: true))
Comment.create!(article: Article.create!(published: false))
expect(Comment.accessible_by(@ability)).to match_array([comment1])
end
it 'should only read articles which are published or in visible categories' do
@ability.can :read, Article, category: { visible: true }
@ability.can :read, Article, published: true
article1 = Article.create!(published: true)
Article.create!(published: false)
article3 = Article.create!(published: false, category: Category.create!(visible: true))
expect(Article.accessible_by(@ability)).to match_array([article1, article3])
end
it 'should only read categories once even if they have multiple articles' do
@ability.can :read, Category, articles: { published: true }
@ability.can :read, Article, published: true
category = Category.create!
Article.create!(published: true, category: category)
Article.create!(published: true, category: category)
expect(Category.accessible_by(@ability)).to match_array([category])
end
it 'only reads comments for visible categories through articles' do
@ability.can :read, Comment, article: { category: { visible: true } }
comment1 = Comment.create!(article: Article.create!(category: Category.create!(visible: true)))
Comment.create!(article: Article.create!(category: Category.create!(visible: false)))
expect(Comment.accessible_by(@ability)).to match_array([comment1])
expect(Comment.accessible_by(@ability).count).to eq(1)
end
it 'allows conditions in SQL and merge with hash conditions' do
@ability.can :read, Article, published: true
@ability.can :read, Article, ['secret=?', true]
article1 = Article.create!(published: true, secret: false)
article2 = Article.create!(published: true, secret: true)
article3 = Article.create!(published: false, secret: true)
Article.create!(published: false, secret: false)
expect(Article.accessible_by(@ability)).to match_array([article1, article2, article3])
end
it 'allows a scope for conditions' do
@ability.can :read, Article, Article.where(secret: true)
article1 = Article.create!(secret: true)
Article.create!(secret: false)
expect(Article.accessible_by(@ability)).to match_array([article1])
end
it 'fetches only associated records when using with a scope for conditions' do
@ability.can :read, Article, Article.where(secret: true)
category1 = Category.create!(visible: false)
category2 = Category.create!(visible: true)
article1 = Article.create!(secret: true, category: category1)
Article.create!(secret: true, category: category2)
expect(category1.articles.accessible_by(@ability)).to match_array([article1])
end
it 'raises an exception when trying to merge scope with other conditions' do
@ability.can :read, Article, published: true
@ability.can :read, Article, Article.where(secret: true)
expect { Article.accessible_by(@ability) }
.to raise_error(CanCan::Error,
'Unable to merge an Active Record scope with other conditions. ' \
'Instead use a hash or SQL for read Article ability.')
end
it 'does not raise an exception when the rule with scope is suppressed' do
@ability.can :read, Article, published: true
@ability.can :read, Article, Article.where(secret: true)
@ability.cannot :read, Article
expect { Article.accessible_by(@ability) }.not_to raise_error
end
it 'recognises empty scopes and compresses them' do
@ability.can :read, Article, published: true
@ability.can :read, Article, Article.all
expect { Article.accessible_by(@ability) }.not_to raise_error
end
it 'does not allow to fetch records when ability with just block present' do
@ability.can :read, Article do
false
end
expect { Article.accessible_by(@ability) }.to raise_error(CanCan::Error)
end
it 'should support more than one deeply nested conditions' do
@ability.can :read, Comment, article: {
category: {
name: 'foo', visible: true
}
}
expect { Comment.accessible_by(@ability) }.to_not raise_error
end
it 'does not allow to check ability on object against SQL conditions without block' do
@ability.can :read, Article, ['secret=?', true]
expect { @ability.can? :read, Article.new }.to raise_error(CanCan::Error)
end
it 'has false conditions if no abilities match' do
expect(@ability.model_adapter(Article, :read).conditions).to eq(false_condition)
end
it 'returns false conditions for cannot clause' do
@ability.cannot :read, Article
expect(@ability.model_adapter(Article, :read).conditions).to eq(false_condition)
end
it 'returns SQL for single `can` definition in front of default `cannot` condition' do
@ability.cannot :read, Article
@ability.can :read, Article, published: false, secret: true
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(
SELECT "articles".*
FROM "articles"
WHERE "articles"."published" = #{false_v} AND "articles"."secret" = #{true_v}))
end
it 'returns true condition for single `can` definition in front of default `can` condition' do
@ability.can :read, Article
@ability.can :read, Article, published: false, secret: true
expect(@ability.model_adapter(Article, :read).conditions).to eq({})
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(SELECT "articles".* FROM "articles"))
end
it 'returns `false condition` for single `cannot` definition in front of default `cannot` condition' do
@ability.cannot :read, Article
@ability.cannot :read, Article, published: false, secret: true
expect(@ability.model_adapter(Article, :read).conditions).to eq(false_condition)
end
it 'returns `not (sql)` for single `cannot` definition in front of default `can` condition' do
@ability.can :read, Article
@ability.cannot :read, Article, published: false, secret: true
expect(@ability.model_adapter(Article, :read).conditions)
.to orderlessly_match(
%["not (#{@article_table}"."published" = #{false_v} AND "#{@article_table}"."secret" = #{true_v})]
)
end
it 'returns appropriate sql conditions in complex case' do
@ability.can :read, Article
@ability.can :manage, Article, id: 1
@ability.can :update, Article, published: true
@ability.cannot :update, Article, secret: true
expect(@ability.model_adapter(Article, :update).conditions)
.to eq(%[not ("#{@article_table}"."secret" = #{true_v}) ] +
%[AND (("#{@article_table}"."published" = #{true_v}) ] +
%[OR ("#{@article_table}"."id" = 1))])
expect(@ability.model_adapter(Article, :manage).conditions).to eq(id: 1)
expect(@ability.model_adapter(Article, :read).conditions).to eq({})
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(SELECT "articles".* FROM "articles"))
end
it 'returns appropriate sql conditions in complex case with nested joins' do
@ability.can :read, Comment, article: { category: { visible: true } }
expect(@ability.model_adapter(Comment, :read).conditions).to eq(Category.table_name.to_sym => { visible: true })
end
it 'returns appropriate sql conditions in complex case with nested joins of different depth' do
@ability.can :read, Comment, article: { published: true, category: { visible: true } }
expect(@ability.model_adapter(Comment, :read).conditions)
.to eq(Article.table_name.to_sym => { published: true }, Category.table_name.to_sym => { visible: true })
end
it 'does not forget conditions when calling with SQL string' do
@ability.can :read, Article, published: true
@ability.can :read, Article, ['secret = ?', false]
adapter = @ability.model_adapter(Article, :read)
2.times do
expect(adapter.conditions).to eq(%[(secret = #{false_v}) OR ("#{@article_table}"."published" = #{true_v})])
end
end
it 'has nil joins if no rules' do
expect(@ability.model_adapter(Article, :read).joins).to be_nil
end
context 'if rules got compressed' do
it 'has nil joins' do
@ability.can :read, Comment, article: { category: { visible: true } }
@ability.can :read, Comment
expect(@ability.model_adapter(Comment, :read))
.to generate_sql("SELECT \"#{@comment_table}\".* FROM \"#{@comment_table}\"")
expect(@ability.model_adapter(Comment, :read).joins).to be_nil
end
end
context 'if rules did not get compressed' do
before :each do
CanCan.rules_compressor_enabled = false
end
it 'has joins' do
@ability.can :read, Comment, article: { category: { visible: true } }
@ability.can :read, Comment
expect(@ability.model_adapter(Comment, :read).joins).to be_present
end
end
it 'has nil joins if no nested hashes specified in conditions' do
@ability.can :read, Article, published: false
@ability.can :read, Article, secret: true
expect(@ability.model_adapter(Article, :read).joins).to be_nil
end
it 'merges separate joins into a single array' do
@ability.can :read, Article, project: { blocked: false }
@ability.can :read, Article, company: { admin: true }
expect(@ability.model_adapter(Article, :read).joins.inspect).to orderlessly_match(%i[company project].inspect)
end
it 'merges same joins into a single array' do
@ability.can :read, Article, project: { blocked: false }
@ability.can :read, Article, project: { admin: true }
expect(@ability.model_adapter(Article, :read).joins).to eq([:project])
end
it 'merges nested and non-nested joins' do
@ability.can :read, Article, project: { blocked: false }
@ability.can :read, Article, project: { comments: { spam: true } }
expect(@ability.model_adapter(Article, :read).joins).to eq([{ project: [:comments] }])
end
it 'merges :all conditions with other conditions' do
user = User.create!
article = Article.create!(user: user)
ability = Ability.new(user)
ability.can :manage, :all
ability.can :manage, Article, user_id: user.id
expect(Article.accessible_by(ability)).to eq([article])
end
it 'should not execute a scope when checking ability on the class' do
relation = Article.where(secret: true)
@ability.can :read, Article, relation do |article|
article.secret == true
end
allow(relation).to receive(:count).and_raise('Unexpected scope execution.')
expect { @ability.can? :read, Article }.not_to raise_error
end
it 'should ignore cannot rules with attributes when querying' do
user = User.create!
article = Article.create!(user: user)
ability = Ability.new(user)
ability.can :read, Article
ability.cannot :read, Article, :secret
expect(Article.accessible_by(ability)).to eq([article])
end
describe 'when can? is used with a Hash (nested resources)' do
it 'verifies parent equality correctly' do
user1 = User.create!(name: 'user1')
user2 = User.create!(name: 'user2')
category = Category.create!(name: 'cat')
article1 = Article.create!(name: 'article1', category: category, user: user1)
article2 = Article.create!(name: 'article2', category: category, user: user2)
comment1 = Comment.create!(article: article1)
comment2 = Comment.create!(article: article2)
ability1 = Ability.new(user1)
ability1.can :read, Article
ability1.can :manage, Article, user: user1
ability1.can :manage, Comment, article: user1.articles
expect(ability1.can?(:manage, { article1 => Comment })).to eq(true)
expect(ability1.can?(:manage, { article2 => Comment })).to eq(false)
expect(ability1.can?(:manage, { article1 => comment1 })).to eq(true)
expect(ability1.can?(:manage, { article2 => comment2 })).to eq(false)
ability2 = Ability.new(user2)
expect(ability2.can?(:manage, { article1 => Comment })).to eq(false)
expect(ability2.can?(:manage, { article2 => Comment })).to eq(false)
expect(ability2.can?(:manage, { article1 => comment1 })).to eq(false)
expect(ability2.can?(:manage, { article2 => comment2 })).to eq(false)
end
end
end
end
describe 'when can? is used with a Hash (nested resources)' do
let(:user1) { User.create!(name: 'user1') }
let(:user2) { User.create!(name: 'user2') }
before do
category = Category.create!(name: 'category')
@article1 = Article.create!(name: 'article1', category: category, user: user1)
@article2 = Article.create!(name: 'article2', category: category, user: user2)
@comment1 = Comment.create!(article: @article1)
@comment2 = Comment.create!(article: @article2)
@legacy_comment1 = LegacyComment.create!(article: @article1)
@legacy_comment2 = LegacyComment.create!(article: @article2)
@attachment1 = Attachment.create!(attachable: @article1)
@comment_attachment1 = Attachment.create!(attachable: @comment1)
@attachment2 = Attachment.create!(attachable: @article2)
@comment_attachment2 = Attachment.create!(attachable: @comment2)
end
context 'when conditions are defined using the parent model' do
let(:ability) do
Ability.new(user1).tap do |ability|
ability.can :read, Article
ability.can :manage, Article, user: user1
ability.can :manage, Comment, article: user1.articles
ability.can :manage, LegacyComment, article: user1.articles
ability.can :manage, Attachment, attachable: user1.articles
ability.can :manage, Attachment, attachable: user1.comments
end
end
it 'verifies parent equality correctly' do
expect(ability.can?(:manage, { @article1 => Comment })).to eq(true)
expect(ability.can?(:manage, { @article1 => LegacyComment })).to eq(true)
expect(ability.can?(:manage, { @article1 => @comment1 })).to eq(true)
expect(ability.can?(:manage, { @article1 => @legacy_comment1 })).to eq(true)
expect(ability.can?(:manage, { @article2 => Comment })).to eq(false)
expect(ability.can?(:manage, { @article2 => LegacyComment })).to eq(false)
expect(ability.can?(:manage, { @article2 => @legacy_comment2 })).to eq(false)
end
context 'when the association is polymorphic' do
it 'verifies parent equality correctly' do
expect(ability.can?(:manage, { @article1 => Attachment })).to eq(true)
expect(ability.can?(:manage, { @article1 => @attachment1 })).to eq(true)
expect(ability.can?(:manage, { @comment1 => Attachment })).to eq(true)
expect(ability.can?(:manage, { @comment1 => @comment_attachment1 })).to eq(true)
expect(ability.can?(:manage, { @article2 => Attachment })).to eq(false)
expect(ability.can?(:manage, { @article2 => @attachment2 })).to eq(false)
expect(ability.can?(:manage, { @comment2 => Attachment })).to eq(false)
expect(ability.can?(:manage, { @comment2 => @comment_attachment2 })).to eq(false)
end
end
end
context 'when conditions are defined using the parent id' do
let(:ability) do
Ability.new(user1).tap do |ability|
ability.can :read, Article
ability.can :manage, Article, user_id: user1.id
ability.can :manage, Comment, article_id: user1.article_ids
ability.can :manage, LegacyComment, post_id: user1.article_ids
ability.can :manage, Attachment, attachable_id: user1.article_ids
end
end
it 'verifies parent equality correctly' do
expect(ability.can?(:manage, { @article1 => Comment })).to eq(true)
expect(ability.can?(:manage, { @article1 => LegacyComment })).to eq(true)
expect(ability.can?(:manage, { @article1 => @comment1 })).to eq(true)
expect(ability.can?(:manage, { @article1 => @legacy_comment1 })).to eq(true)
expect(ability.can?(:manage, { @article2 => Comment })).to eq(false)
expect(ability.can?(:manage, { @article2 => LegacyComment })).to eq(false)
expect(ability.can?(:manage, { @article2 => @legacy_comment2 })).to eq(false)
end
context 'when the association is polymorphic' do
it 'verifies parent equality correctly' do
expect(ability.can?(:manage, { @article1 => Attachment })).to eq(true)
expect(ability.can?(:manage, { @article1 => @attachment1 })).to eq(true)
expect(ability.can?(:manage, { @comment1 => Attachment })).to eq(true)
expect(ability.can?(:manage, { @comment1 => @comment_attachment1 })).to eq(true)
expect(ability.can?(:manage, { @article2 => Attachment })).to eq(false)
expect(ability.can?(:manage, { @article2 => @attachment2 })).to eq(false)
expect(ability.can?(:manage, { @comment2 => Attachment })).to eq(false)
expect(ability.can?(:manage, { @comment2 => @comment_attachment2 })).to eq(false)
end
end
end
end
unless CanCan::ModelAdapters::ActiveRecordAdapter.version_lower?('5.0.0')
context 'base behaviour subquery specific' do
before :each do
CanCan.accessible_by_strategy = :subquery
end
it 'allows ordering via relations' do
@ability.can :read, Comment, article: { category: { visible: true } }
comment1 = Comment.create!(article: Article.create!(name: 'B', category: Category.create!(visible: true)))
comment2 = Comment.create!(article: Article.create!(name: 'A', category: Category.create!(visible: true)))
Comment.create!(article: Article.create!(category: Category.create!(visible: false)))
# doesn't work without explicitly calling a join on AR 5+,
# but does before that (where we don't use subqueries at all)
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
expect { Comment.accessible_by(@ability).order('articles.name').to_a }
.to raise_error(ActiveRecord::StatementInvalid)
else
expect(Comment.accessible_by(@ability).order('articles.name'))
.to match_array([comment2, comment1])
end
# works with the explicit join
expect(Comment.accessible_by(@ability).joins(:article).order('articles.name'))
.to match_array([comment2, comment1])
end
end
end
context 'base behaviour left_join specific' do
before :each do
CanCan.accessible_by_strategy = :left_join
end
it 'allows ordering via relations in sqlite' do
skip unless sqlite?
@ability.can :read, Comment, article: { category: { visible: true } }
comment1 = Comment.create!(article: Article.create!(name: 'B', category: Category.create!(visible: true)))
comment2 = Comment.create!(article: Article.create!(name: 'A', category: Category.create!(visible: true)))
Comment.create!(article: Article.create!(category: Category.create!(visible: false)))
# works without explicitly calling a join
expect(Comment.accessible_by(@ability).order('articles.name')).to match_array([comment2, comment1])
# works with the explicit join in AR 5.2+ and AR 4.2
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.2.0')
expect(Comment.accessible_by(@ability).joins(:article).order('articles.name'))
.to match_array([comment2, comment1])
elsif CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
expect { Comment.accessible_by(@ability).joins(:article).order('articles.name').to_a }
.to raise_error(ActiveRecord::StatementInvalid)
else
expect(Comment.accessible_by(@ability).joins(:article).order('articles.name'))
.to match_array([comment2, comment1])
end
end
# this fails on Postgres. see https://github.com/CanCanCommunity/cancancan/pull/608
it 'fails to order via relations in postgres on AR 5+' do
skip unless postgres?
@ability.can :read, Comment, article: { category: { visible: true } }
comment1 = Comment.create!(article: Article.create!(name: 'B', category: Category.create!(visible: true)))
comment2 = Comment.create!(article: Article.create!(name: 'A', category: Category.create!(visible: true)))
Comment.create!(article: Article.create!(category: Category.create!(visible: false)))
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
# doesn't work with or without the join
expect { Comment.accessible_by(@ability).order('articles.name').to_a }
.to raise_error(ActiveRecord::StatementInvalid)
expect { Comment.accessible_by(@ability).joins(:article).order('articles.name').to_a }
.to raise_error(ActiveRecord::StatementInvalid)
else
expect(Comment.accessible_by(@ability).order('articles.name'))
.to match_array([comment2, comment1])
expect(Comment.accessible_by(@ability).joins(:article).order('articles.name'))
.to match_array([comment2, comment1])
end
end
end
it 'allows an empty array to be used as a condition for a has_many, but this is never a passing condition' do
a1 = Article.create!
a2 = Article.create!
a2.comments = [Comment.create!]
@ability.can :read, Article, comment_ids: []
expect(@ability.can?(:read, a1)).to eq(false)
expect(@ability.can?(:read, a2)).to eq(false)
expect(Article.accessible_by(@ability)).to eq([])
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(
SELECT "articles".*
FROM "articles"
WHERE 1=0))
end
end
it 'allows a nil to be used as a condition for a has_many - with join' do
a1 = Article.create!
a2 = Article.create!
a2.comments = [Comment.create!]
@ability.can :read, Article, comments: { id: nil }
expect(@ability.can?(:read, a1)).to eq(true)
expect(@ability.can?(:read, a2)).to eq(false)
expect(Article.accessible_by(@ability)).to eq([a1])
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(
SELECT "articles".*
FROM "articles"
WHERE "articles"."id" IN (SELECT "articles"."id" FROM "articles"
LEFT OUTER JOIN "comments" ON "comments"."article_id" = "articles"."id"
WHERE "comments"."id" IS NULL)))
end
end
it 'allows several nils to be used as a condition for a has_many - with join' do
a1 = Article.create!
a2 = Article.create!
a2.comments = [Comment.create!]
@ability.can :read, Article, comments: { id: nil, spam: nil }
expect(@ability.can?(:read, a1)).to eq(true)
expect(@ability.can?(:read, a2)).to eq(false)
expect(Article.accessible_by(@ability)).to eq([a1])
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(
SELECT "articles".*
FROM "articles"
WHERE "articles"."id" IN (SELECT "articles"."id" FROM "articles"
LEFT OUTER JOIN "comments" ON "comments"."article_id" = "articles"."id"
WHERE "comments"."id" IS NULL AND "comments"."spam" IS NULL)))
end
end
it 'doesn\'t permit anything if a nil is used as a condition for a has_many alongside other attributes' do
a1 = Article.create!
a2 = Article.create!
a2.comments = [Comment.create!(spam: true)]
a3 = Article.create!
a3.comments = [Comment.create!(spam: false)]
# if we are checking for `id: nil` and any other criteria, we should never return any Article.
# either the Article has Comments, which means `id: nil` fails.
# or the Article has no Comments, which means `spam: true` fails.
@ability.can :read, Article, comments: { id: nil, spam: true }
expect(@ability.can?(:read, a1)).to eq(false)
expect(@ability.can?(:read, a2)).to eq(false)
expect(@ability.can?(:read, a3)).to eq(false)
expect(Article.accessible_by(@ability)).to eq([])
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
expect(@ability.model_adapter(Article, :read)).to generate_sql(%(
SELECT "articles".*
FROM "articles"
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | true |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/active_record_5_adapter_spec.rb | spec/cancan/model_adapters/active_record_5_adapter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
describe CanCan::ModelAdapters::ActiveRecord5Adapter do
CanCan.valid_accessible_by_strategies.each do |strategy|
context "with sqlite3 and #{strategy} strategy" do
before :each do
CanCan.accessible_by_strategy = strategy
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:shapes) do |t|
t.integer :color, default: 0, null: false
end
create_table(:things) do |t|
t.string :size, default: 'big', null: false
end
create_table(:discs) do |t|
t.integer :color, default: 0, null: false
t.integer :shape, default: 3, null: false
end
end
unless defined?(Thing)
class Thing < ActiveRecord::Base
enum size: { big: 'big', medium: 'average', small: 'small' }
end
end
unless defined?(Shape)
class Shape < ActiveRecord::Base
enum color: %i[red green blue]
end
end
unless defined?(Disc)
class Disc < ActiveRecord::Base
enum color: %i[red green blue]
enum shape: { triangle: 3, rectangle: 4 }
end
end
end
subject(:ability) { Ability.new(nil) }
context 'when enums use integers as values' do
let(:red) { Shape.create!(color: :red) }
let(:green) { Shape.create!(color: :green) }
let(:blue) { Shape.create!(color: :blue) }
context 'when the condition contains a single value' do
before do
ability.can :read, Shape, color: :green
end
it 'can check ability on single models' do
is_expected.not_to be_able_to(:read, red)
is_expected.to be_able_to(:read, green)
is_expected.not_to be_able_to(:read, blue)
end
it 'can use accessible_by helper' do
accessible = Shape.accessible_by(ability)
expect(accessible).to contain_exactly(green)
end
end
context 'when the condition contains multiple values' do
before do
ability.can :update, Shape, color: %i[red blue]
end
it 'can check ability on single models' do
is_expected.to be_able_to(:update, red)
is_expected.not_to be_able_to(:update, green)
is_expected.to be_able_to(:update, blue)
end
it 'can use accessible_by helper' do
accessible = Shape.accessible_by(ability, :update)
expect(accessible).to contain_exactly(red, blue)
end
end
end
context 'when enums use strings as values' do
let(:big) { Thing.create!(size: :big) }
let(:medium) { Thing.create!(size: :medium) }
let(:small) { Thing.create!(size: :small) }
context 'when the condition contains a single value' do
before do
ability.can :read, Thing, size: :medium
end
it 'can check ability on single models' do
is_expected.not_to be_able_to(:read, big)
is_expected.to be_able_to(:read, medium)
is_expected.not_to be_able_to(:read, small)
end
it 'can use accessible_by helper' do
expect(Thing.accessible_by(ability)).to contain_exactly(medium)
end
context 'when a rule is overridden' do
before do
ability.cannot :read, Thing, size: 'average'
end
it 'is recognised correctly' do
is_expected.not_to be_able_to(:read, medium)
expect(Thing.accessible_by(ability)).to be_empty
end
end
end
context 'when the condition contains multiple values' do
before do
ability.can :update, Thing, size: %i[big small]
end
it 'can check ability on single models' do
is_expected.to be_able_to(:update, big)
is_expected.not_to be_able_to(:update, medium)
is_expected.to be_able_to(:update, small)
end
it 'can use accessible_by helper' do
expect(Thing.accessible_by(ability, :update)).to contain_exactly(big, small)
end
end
end
context 'when multiple enums are present' do
let(:red_triangle) { Disc.create!(color: :red, shape: :triangle) }
let(:green_triangle) { Disc.create!(color: :green, shape: :triangle) }
let(:green_rectangle) { Disc.create!(color: :green, shape: :rectangle) }
let(:blue_rectangle) { Disc.create!(color: :blue, shape: :rectangle) }
before do
ability.can :read, Disc, color: :green, shape: :rectangle
end
it 'can check ability on single models' do
is_expected.not_to be_able_to(:read, red_triangle)
is_expected.not_to be_able_to(:read, green_triangle)
is_expected.to be_able_to(:read, green_rectangle)
is_expected.not_to be_able_to(:read, blue_rectangle)
end
it 'can use accessible_by helper' do
expect(Disc.accessible_by(ability)).to contain_exactly(green_rectangle)
end
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/has_and_belongs_to_many_spec.rb | spec/cancan/model_adapters/has_and_belongs_to_many_spec.rb | require 'spec_helper'
RSpec.describe CanCan::ModelAdapters::ActiveRecord5Adapter do
let(:ability) { double.extend(CanCan::Ability) }
let(:users_table) { User.table_name }
let(:posts_table) { Post.table_name }
before :all do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:people) do |t|
t.string :name
t.timestamps null: false
end
create_table(:houses) do |t|
t.boolean :restructured, default: true
t.timestamps null: false
end
create_table(:houses_people) do |t|
t.integer :person_id
t.integer :house_id
t.timestamps null: false
end
end
class Person < ActiveRecord::Base
has_and_belongs_to_many :houses
end
class House < ActiveRecord::Base
has_and_belongs_to_many :people
end
end
before do
@person1 = Person.create!
@person2 = Person.create!
@house1 = House.create!(people: [@person1])
@house2 = House.create!(restructured: false, people: [@person1, @person2])
@house3 = House.create!(people: [@person2])
ability.can :read, House, people: { id: @person1.id }
end
unless CanCan::ModelAdapters::ActiveRecordAdapter.version_lower?('5.0.0')
describe 'fetching of records - joined_alias_subquery strategy' do
before do
CanCan.accessible_by_strategy = :joined_alias_exists_subquery
end
it 'it retreives the records correctly' do
houses = House.accessible_by(ability)
expect(houses).to match_array [@house2, @house1]
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
it 'generates the correct query' do
expect(ability.model_adapter(House, :read))
.to generate_sql("SELECT \"houses\".*
FROM \"houses\"
JOIN \"houses\" AS \"houses_alias\" ON \"houses_alias\".\"id\" = \"houses\".\"id\"
WHERE (EXISTS (SELECT 1
FROM \"houses\"
LEFT OUTER JOIN \"houses_people\" ON \"houses_people\".\"house_id\" = \"houses\".\"id\"
LEFT OUTER JOIN \"people\" ON \"people\".\"id\" = \"houses_people\".\"person_id\"
WHERE
\"people\".\"id\" = #{@person1.id} AND
(\"houses\".\"id\" = \"houses_alias\".\"id\") LIMIT 1))
")
end
end
end
describe 'fetching of records - joined_alias_each_rule_as_exists_subquery strategy' do
before do
CanCan.accessible_by_strategy = :joined_alias_each_rule_as_exists_subquery
end
it 'it retreives the records correctly' do
houses = House.accessible_by(ability)
expect(houses).to match_array [@house2, @house1]
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
it 'generates the correct query' do
expect(ability.model_adapter(House, :read))
.to generate_sql("SELECT \"houses\".*
FROM \"houses\"
JOIN \"houses\" AS \"houses_alias\" ON \"houses_alias\".\"id\" = \"houses\".\"id\"
WHERE (EXISTS (SELECT 1
FROM \"houses\"
INNER JOIN \"houses_people\" ON \"houses_people\".\"house_id\" = \"houses\".\"id\"
INNER JOIN \"people\" ON \"people\".\"id\" = \"houses_people\".\"person_id\"
WHERE (\"houses\".\"id\" = \"houses_alias\".\"id\") AND
(\"people\".\"id\" = #{@person1.id})
LIMIT 1))
")
end
end
end
describe 'fetching of records - subquery strategy' do
before do
CanCan.accessible_by_strategy = :subquery
end
it 'it retrieves the records correctly' do
houses = House.accessible_by(ability)
expect(houses).to match_array [@house2, @house1]
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
it 'generates the correct query' do
expect(ability.model_adapter(House, :read))
.to generate_sql("SELECT \"houses\".*
FROM \"houses\"
WHERE \"houses\".\"id\" IN
(SELECT \"houses\".\"id\"
FROM \"houses\"
LEFT OUTER JOIN \"houses_people\" ON \"houses_people\".\"house_id\" = \"houses\".\"id\"
LEFT OUTER JOIN \"people\" ON \"people\".\"id\" = \"houses_people\".\"person_id\"
WHERE \"people\".\"id\" = #{@person1.id})
")
end
end
end
end
describe 'fetching of records - left_join strategy' do
before do
CanCan.accessible_by_strategy = :left_join
end
it 'it retrieves the records correctly' do
houses = House.accessible_by(ability)
expect(houses).to match_array [@house2, @house1]
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
it 'generates the correct query' do
expect(ability.model_adapter(House, :read)).to generate_sql(%(
SELECT DISTINCT "houses".*
FROM "houses"
LEFT OUTER JOIN "houses_people" ON "houses_people"."house_id" = "houses"."id"
LEFT OUTER JOIN "people" ON "people"."id" = "houses_people"."person_id"
WHERE "people"."id" = #{@person1.id}))
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/accessible_by_integration_spec.rb | spec/cancan/model_adapters/accessible_by_integration_spec.rb | # frozen_string_literal: true
require 'spec_helper'
# integration tests for latest ActiveRecord version.
RSpec.describe CanCan::ModelAdapters::ActiveRecord5Adapter do
let(:ability) { double.extend(CanCan::Ability) }
let(:users_table) { Post.table_name }
let(:posts_table) { Post.table_name }
let(:likes_table) { Like.table_name }
before :each do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:users) do |t|
t.string :name
t.timestamps null: false
end
create_table(:posts) do |t|
t.string :title
t.boolean :published, default: true
t.integer :user_id
t.timestamps null: false
end
create_table(:likes) do |t|
t.integer :post_id
t.integer :user_id
t.timestamps null: false
end
create_table(:editors) do |t|
t.integer :post_id
t.integer :user_id
t.timestamps null: false
end
end
class User < ActiveRecord::Base
has_many :posts
has_many :likes
has_many :editors
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :likes
has_many :editors
end
class Like < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Editor < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
end
before do
@user1 = User.create!
@user2 = User.create!
@post1 = Post.create!(title: 'post1', user: @user1)
@post2 = Post.create!(user: @user1, published: false)
@post3 = Post.create!(user: @user2)
@like1 = Like.create!(post: @post1, user: @user1)
@like2 = Like.create!(post: @post1, user: @user2)
@editor1 = Editor.create(user: @user1, post: @post2)
ability.can :read, Post, user_id: @user1
ability.can :read, Post, editors: { user_id: @user1 }
end
describe 'preloading of associations' do
it 'preloads associations correctly' do
posts = Post.accessible_by(ability).where(published: true).includes(likes: :user)
expect(posts[0].association(:likes)).to be_loaded
expect(posts[0].likes[0].association(:user)).to be_loaded
end
end
describe 'filtering of results' do
it 'adds the where clause correctly' do
posts = Post.accessible_by(ability).where(published: true)
expect(posts.length).to eq 1
end
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('5.0.0')
describe 'selecting custom columns' do
it 'extracts custom columns correctly' do
posts = Post.accessible_by(ability).where(published: true).select('title as mytitle')
expect(posts[0].mytitle).to eq 'post1'
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/conditions_normalizer_spec.rb | spec/cancan/model_adapters/conditions_normalizer_spec.rb | require 'spec_helper'
RSpec.describe CanCan::ModelAdapters::ConditionsNormalizer do
before do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:articles) do |t|
end
create_table(:users) do |t|
t.string :name
end
create_table(:comments) do |t|
end
create_table(:spread_comments) do |t|
t.integer :article_id
t.integer :comment_id
end
create_table(:legacy_mentions) do |t|
t.integer :user_id
t.integer :article_id
end
create_table(:attachments) do |t|
t.references :record, polymorphic: true
t.integer :blob_id
end
create_table(:blob) do |t|
end
end
class Article < ActiveRecord::Base
has_many :spread_comments
has_many :comments, through: :spread_comments
has_many :mentions
has_many :mentioned_users, through: :mentions, source: :user
has_many :attachments, as: :record
end
class Comment < ActiveRecord::Base
has_many :spread_comments
has_many :articles, through: :spread_comments
end
class SpreadComment < ActiveRecord::Base
belongs_to :comment
belongs_to :article
end
class Mention < ActiveRecord::Base
self.table_name = 'legacy_mentions'
belongs_to :article
belongs_to :user
end
class User < ActiveRecord::Base
has_many :mentions
has_many :mentioned_articles, through: :mentions, source: :article
end
class Attachment < ActiveRecord::Base
belongs_to :record, polymorphic: true
belongs_to :blob
end
class Blob < ActiveRecord::Base
has_many :attachments
has_many :articles, through: :attachments, source: :record, source_type: 'Article'
end
end
it 'simplifies has_many through associations' do
rule = CanCan::Rule.new(true, :read, Comment, articles: { mentioned_users: { name: 'pippo' } })
CanCan::ModelAdapters::ConditionsNormalizer.normalize(Comment, [rule])
expect(rule.conditions).to eq(spread_comments: { article: { mentions: { user: { name: 'pippo' } } } })
end
it 'does not simplifies has_many through polymorphic associations' do
rule = CanCan::Rule.new(true, :read, Blob, articles: { id: 11 })
CanCan::ModelAdapters::ConditionsNormalizer.normalize(Blob, [rule])
expect(rule.conditions).to eq(articles: { id: 11 })
end
it 'normalizes the has_one through associations' do
class Supplier < ActiveRecord::Base
has_one :accountant
has_one :account_history, through: :accountant
end
class Accountant < ActiveRecord::Base
belongs_to :supplier
has_one :account_history
end
class AccountHistory < ActiveRecord::Base
belongs_to :accountant
end
rule = CanCan::Rule.new(true, :read, Supplier, account_history: { name: 'pippo' })
CanCan::ModelAdapters::ConditionsNormalizer.normalize(Supplier, [rule])
expect(rule.conditions).to eq(accountant: { account_history: { name: 'pippo' } })
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/active_record_4_adapter_spec.rb | spec/cancan/model_adapters/active_record_4_adapter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
if CanCan::ModelAdapters::ActiveRecordAdapter.version_lower?('5.0.0')
describe CanCan::ModelAdapters::ActiveRecord4Adapter do
# only the `left_join` strategy works in AR4
CanCan.valid_accessible_by_strategies.each do |strategy|
context "with sqlite3 and #{strategy} strategy" do
before :each do
CanCan.accessible_by_strategy = strategy
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:parents) do |t|
t.timestamps null: false
end
create_table(:children) do |t|
t.timestamps null: false
t.integer :parent_id
end
end
class Parent < ActiveRecord::Base
has_many :children, -> { order(id: :desc) }
end
class Child < ActiveRecord::Base
belongs_to :parent
end
(@ability = double).extend(CanCan::Ability)
end
it 'respects scope on included associations' do
@ability.can :read, [Parent, Child]
parent = Parent.create!
child1 = Child.create!(parent: parent, created_at: 1.hours.ago)
child2 = Child.create!(parent: parent, created_at: 2.hours.ago)
expect(Parent.accessible_by(@ability).order(created_at: :asc).includes(:children).first.children)
.to eq [child2, child1]
end
if CanCan::ModelAdapters::ActiveRecordAdapter.version_greater_or_equal?('4.1.0')
it 'allows filters on enums' do
ActiveRecord::Schema.define do
create_table(:shapes) do |t|
t.integer :color, default: 0, null: false
end
end
class Shape < ActiveRecord::Base
enum color: %i[red green blue] unless defined_enums.key? 'color'
end
red = Shape.create!(color: :red)
green = Shape.create!(color: :green)
blue = Shape.create!(color: :blue)
# A condition with a single value.
@ability.can :read, Shape, color: Shape.colors[:green]
expect(@ability.cannot?(:read, red)).to be true
expect(@ability.can?(:read, green)).to be true
expect(@ability.cannot?(:read, blue)).to be true
accessible = Shape.accessible_by(@ability)
expect(accessible).to contain_exactly(green)
# A condition with multiple values.
@ability.can :update, Shape, color: [Shape.colors[:red],
Shape.colors[:blue]]
expect(@ability.can?(:update, red)).to be true
expect(@ability.cannot?(:update, green)).to be true
expect(@ability.can?(:update, blue)).to be true
accessible = Shape.accessible_by(@ability, :update)
expect(accessible).to contain_exactly(red, blue)
end
it 'allows dual filter on enums' do
ActiveRecord::Schema.define do
create_table(:discs) do |t|
t.integer :color, default: 0, null: false
t.integer :shape, default: 3, null: false
end
end
class Disc < ActiveRecord::Base
enum color: %i[red green blue] unless defined_enums.key? 'color'
enum shape: { triangle: 3, rectangle: 4 } unless defined_enums.key? 'shape'
end
red_triangle = Disc.create!(color: Disc.colors[:red], shape: Disc.shapes[:triangle])
green_triangle = Disc.create!(color: Disc.colors[:green], shape: Disc.shapes[:triangle])
green_rectangle = Disc.create!(color: Disc.colors[:green], shape: Disc.shapes[:rectangle])
blue_rectangle = Disc.create!(color: Disc.colors[:blue], shape: Disc.shapes[:rectangle])
# A condition with a dual filter.
@ability.can :read, Disc, color: Disc.colors[:green], shape: Disc.shapes[:rectangle]
expect(@ability.cannot?(:read, red_triangle)).to be true
expect(@ability.cannot?(:read, green_triangle)).to be true
expect(@ability.can?(:read, green_rectangle)).to be true
expect(@ability.cannot?(:read, blue_rectangle)).to be true
accessible = Disc.accessible_by(@ability)
expect(accessible).to contain_exactly(green_rectangle)
end
end
end
context 'with postgresql' do
before :each do
connect_db
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table(:parents) do |t|
t.timestamps null: false
end
create_table(:children) do |t|
t.timestamps null: false
t.integer :parent_id
end
end
class Parent < ActiveRecord::Base
has_many :children, -> { order(id: :desc) }
end
class Child < ActiveRecord::Base
belongs_to :parent
end
(@ability = double).extend(CanCan::Ability)
end
it 'allows overlapping conditions in SQL and merge with hash conditions' do
@ability.can :read, Parent, children: { parent_id: 1 }
@ability.can :read, Parent, children: { parent_id: 1 }
parent = Parent.create!
Child.create!(parent: parent, created_at: 1.hours.ago)
Child.create!(parent: parent, created_at: 2.hours.ago)
expect(Parent.accessible_by(@ability)).to eq([parent])
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/spec/cancan/model_adapters/default_adapter_spec.rb | spec/cancan/model_adapters/default_adapter_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe CanCan::ModelAdapters::DefaultAdapter do
it 'is default for generic classes' do
expect(CanCan::ModelAdapters::AbstractAdapter.adapter_class(Object)).to eq(CanCan::ModelAdapters::DefaultAdapter)
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan.rb | lib/cancan.rb | # frozen_string_literal: true
require 'cancan/version'
require 'cancan/config'
require 'cancan/parameter_validators'
require 'cancan/ability'
require 'cancan/rule'
require 'cancan/controller_resource'
require 'cancan/controller_additions'
require 'cancan/model_additions'
require 'cancan/exceptions'
require 'cancan/model_adapters/abstract_adapter'
require 'cancan/model_adapters/default_adapter'
require 'cancan/rules_compressor'
if defined? ActiveRecord
require 'cancan/model_adapters/conditions_extractor'
require 'cancan/model_adapters/conditions_normalizer'
require 'cancan/model_adapters/sti_normalizer'
require 'cancan/model_adapters/active_record_adapter'
require 'cancan/model_adapters/active_record_4_adapter'
require 'cancan/model_adapters/active_record_5_adapter'
require 'cancan/model_adapters/strategies/base'
require 'cancan/model_adapters/strategies/joined_alias_each_rule_as_exists_subquery'
require 'cancan/model_adapters/strategies/joined_alias_exists_subquery'
require 'cancan/model_adapters/strategies/left_join'
require 'cancan/model_adapters/strategies/subquery'
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancancan.rb | lib/cancancan.rb | # frozen_string_literal: true
require 'cancan'
module CanCanCan
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/version.rb | lib/cancan/version.rb | # frozen_string_literal: true
module CanCan
VERSION = '3.6.0'.freeze
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/matchers.rb | lib/cancan/matchers.rb | # frozen_string_literal: true
rspec_module = defined?(RSpec::Core) ? 'RSpec' : 'Spec' # RSpec 1 compatability
if rspec_module == 'RSpec'
require 'rspec/core'
require 'rspec/expectations'
else
ActiveSupport::Deprecation.warn('RSpec < 3 will not be supported in the CanCanCan >= 2.0.0')
end
Kernel.const_get(rspec_module)::Matchers.define :be_able_to do |*args|
match do |ability|
actions = args.first
if actions.is_a? Array
if actions.empty?
false
else
actions.all? { |action| ability.can?(action, *args[1..-1]) }
end
else
ability.can?(*args)
end
end
# Check that RSpec is < 2.99
if !respond_to?(:failure_message) && respond_to?(:failure_message_for_should)
alias_method :failure_message, :failure_message_for_should
end
if !respond_to?(:failure_message_when_negated) && respond_to?(:failure_message_for_should_not)
alias_method :failure_message_when_negated, :failure_message_for_should_not
end
failure_message do
resource = args[1]
if resource.instance_of?(Class)
"expected to be able to #{args.map(&:to_s).join(' ')}"
else
"expected to be able to #{args.map(&:inspect).join(' ')}"
end
end
failure_message_when_negated do
resource = args[1]
if resource.instance_of?(Class)
"expected not to be able to #{args.map(&:to_s).join(' ')}"
else
"expected not to be able to #{args.map(&:inspect).join(' ')}"
end
end
description do
"be able to #{args.map(&:to_s).join(' ')}"
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_additions.rb | lib/cancan/model_additions.rb | # frozen_string_literal: true
module CanCan
# This module adds the accessible_by class method to a model. It is included in the model adapters.
module ModelAdditions
module ClassMethods
# Returns a scope which fetches only the records that the passed ability
# can perform a given action on. The action defaults to :index. This
# is usually called from a controller and passed the +current_ability+.
#
# @articles = Article.accessible_by(current_ability)
#
# Here only the articles which the user is able to read will be returned.
# If the user does not have permission to read any articles then an empty
# result is returned. Since this is a scope it can be combined with any
# other scopes or pagination.
#
# An alternative action can optionally be passed as a second argument.
#
# @articles = Article.accessible_by(current_ability, :update)
#
# Here only the articles which the user can update are returned.
def accessible_by(ability, action = :index, strategy: CanCan.accessible_by_strategy)
CanCan.with_accessible_by_strategy(strategy) do
ability.model_adapter(self, action).database_records
end
end
end
def self.included(base)
base.extend ClassMethods
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/exceptions.rb | lib/cancan/exceptions.rb | # frozen_string_literal: true
module CanCan
# A general CanCan exception
class Error < StandardError; end
# Raised when behavior is not implemented, usually used in an abstract class.
class NotImplemented < Error; end
# Raised when removed code is called, an alternative solution is provided in message.
class ImplementationRemoved < Error; end
# Raised when using check_authorization without calling authorize!
class AuthorizationNotPerformed < Error; end
# Raised when a rule is created with both a block and a hash of conditions
class BlockAndConditionsError < Error; end
# Raised when an unexpected argument is passed as an attribute
class AttributeArgumentError < Error; end
# Raised when using a wrong association name
class WrongAssociationName < Error; end
# This error is raised when a user isn't allowed to access a given controller action.
# This usually happens within a call to ControllerAdditions#authorize! but can be
# raised manually.
#
# raise CanCan::AccessDenied.new("Not authorized!", :read, Article)
#
# The passed message, action, and subject are optional and can later be retrieved when
# rescuing from the exception.
#
# exception.message # => "Not authorized!"
# exception.action # => :read
# exception.subject # => Article
#
# If the message is not specified (or is nil) it will default to "You are not authorized
# to access this page." This default can be overridden by setting default_message.
#
# exception.default_message = "Default error message"
# exception.message # => "Default error message"
#
# See ControllerAdditions#authorize! for more information on rescuing from this exception
# and customizing the message using I18n.
class AccessDenied < Error
attr_reader :action, :subject, :conditions
attr_writer :default_message
def initialize(message = nil, action = nil, subject = nil, conditions = nil)
@message = message
@action = action
@subject = subject
@conditions = conditions
@default_message = I18n.t(:"unauthorized.default", default: 'You are not authorized to access this page.')
end
def to_s
@message || @default_message
end
def inspect
details = %i[action subject conditions message].map do |attribute|
value = instance_variable_get "@#{attribute}"
"#{attribute}: #{value.inspect}" if value.present?
end.compact.join(', ')
"#<#{self.class.name} #{details}>"
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/ability.rb | lib/cancan/ability.rb | # frozen_string_literal: true
require_relative 'ability/rules.rb'
require_relative 'ability/actions.rb'
require_relative 'unauthorized_message_resolver.rb'
require_relative 'ability/strong_parameter_support'
module CanCan
# This module is designed to be included into an Ability class. This will
# provide the "can" methods for defining and checking abilities.
#
# class Ability
# include CanCan::Ability
#
# def initialize(user)
# if user.admin?
# can :manage, :all
# else
# can :read, :all
# end
# end
# end
#
module Ability
include CanCan::Ability::Rules
include CanCan::Ability::Actions
include CanCan::UnauthorizedMessageResolver
include StrongParameterSupport
# Check if the user has permission to perform a given action on an object.
#
# can? :destroy, @project
#
# You can also pass the class instead of an instance (if you don't have one handy).
#
# can? :create, Project
#
# Nested resources can be passed through a hash, this way conditions which are
# dependent upon the association will work when using a class.
#
# can? :create, @category => Project
#
# You can also pass multiple objects to check. You only need to pass a hash
# following the pattern { :any => [many subjects] }. The behaviour is check if
# there is a permission on any of the given objects.
#
# can? :create, {:any => [Project, Rule]}
#
#
# Any additional arguments will be passed into the "can" block definition. This
# can be used to pass more information about the user's request for example.
#
# can? :create, Project, request.remote_ip
#
# can :create, Project do |project, remote_ip|
# # ...
# end
#
# Not only can you use the can? method in the controller and view (see ControllerAdditions),
# but you can also call it directly on an ability instance.
#
# ability.can? :destroy, @project
#
# This makes testing a user's abilities very easy.
#
# def test "user can only destroy projects which he owns"
# user = User.new
# ability = Ability.new(user)
# assert ability.can?(:destroy, Project.new(:user => user))
# assert ability.cannot?(:destroy, Project.new)
# end
#
# Also see the RSpec Matchers to aid in testing.
def can?(action, subject, attribute = nil, *extra_args)
match = extract_subjects(subject).lazy.map do |a_subject|
relevant_rules_for_match(action, a_subject).detect do |rule|
rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute)
end
end.reject(&:nil?).first
match ? match.base_behavior : false
end
# Convenience method which works the same as "can?" but returns the opposite value.
#
# cannot? :destroy, @project
#
def cannot?(*args)
!can?(*args)
end
# Defines which abilities are allowed using two arguments. The first one is the action
# you're setting the permission for, the second one is the class of object you're setting it on.
#
# can :update, Article
#
# You can pass an array for either of these parameters to match any one.
# Here the user has the ability to update or destroy both articles and comments.
#
# can [:update, :destroy], [Article, Comment]
#
# You can pass :all to match any object and :manage to match any action. Here are some examples.
#
# can :manage, :all
# can :update, :all
# can :manage, Project
#
# You can pass a hash of conditions as the third argument. Here the user can only see active projects which he owns.
#
# can :read, Project, :active => true, :user_id => user.id
#
# See ActiveRecordAdditions#accessible_by for how to use this in database queries. These conditions
# are also used for initial attributes when building a record in ControllerAdditions#load_resource.
#
# If the conditions hash does not give you enough control over defining abilities, you can use a block
# along with any Ruby code you want.
#
# can :update, Project do |project|
# project.groups.include?(user.group)
# end
#
# If the block returns true then the user has that :update ability for that project, otherwise he
# will be denied access. The downside to using a block is that it cannot be used to generate
# conditions for database queries.
#
# You can pass custom objects into this "can" method, this is usually done with a symbol
# and is useful if a class isn't available to define permissions on.
#
# can :read, :stats
# can? :read, :stats # => true
#
# IMPORTANT: Neither a hash of conditions nor a block will be used when checking permission on a class.
#
# can :update, Project, :priority => 3
# can? :update, Project # => true
#
# If you pass no arguments to +can+, the action, class, and object will be passed to the block and the
# block will always be executed. This allows you to override the full behavior if the permissions are
# defined in an external source such as the database.
#
# can do |action, object_class, object|
# # check the database and return true/false
# end
#
def can(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(true, action, subject, *attributes_and_conditions, &block))
end
# Defines an ability which cannot be done. Accepts the same arguments as "can".
#
# can :read, :all
# cannot :read, Comment
#
# A block can be passed just like "can", however if the logic is complex it is recommended
# to use the "can" method.
#
# cannot :read, Product do |product|
# product.invisible?
# end
#
def cannot(action = nil, subject = nil, *attributes_and_conditions, &block)
add_rule(Rule.new(false, action, subject, *attributes_and_conditions, &block))
end
# User shouldn't specify targets with names of real actions or it will cause Seg fault
def validate_target(target)
error_message = "You can't specify target (#{target}) as alias because it is real action name"
raise Error, error_message if aliased_actions.values.flatten.include? target
end
def model_adapter(model_class, action)
adapter_class = ModelAdapters::AbstractAdapter.adapter_class(model_class)
adapter_class.new(model_class, relevant_rules_for_query(action, model_class))
end
# See ControllerAdditions#authorize! for documentation.
def authorize!(action, subject, *args)
message = args.last.is_a?(Hash) && args.last.key?(:message) ? args.pop[:message] : nil
if cannot?(action, subject, *args)
message ||= unauthorized_message(action, subject)
raise AccessDenied.new(message, action, subject, args)
end
subject
end
def attributes_for(action, subject)
attributes = {}
relevant_rules(action, subject).map do |rule|
attributes.merge!(rule.attributes_from_conditions) if rule.base_behavior
end
attributes
end
def has_block?(action, subject)
relevant_rules(action, subject).any?(&:only_block?)
end
def has_raw_sql?(action, subject)
relevant_rules(action, subject).any?(&:only_raw_sql?)
end
# Copies all rules and aliased actions of the given +CanCan::Ability+ and adds them to +self+.
# class ReadAbility
# include CanCan::Ability
#
# def initialize
# can :read, User
# alias_action :show, :index, to: :see
# end
# end
#
# class WritingAbility
# include CanCan::Ability
#
# def initialize
# can :edit, User
# alias_action :create, :update, to: :modify
# end
# end
#
# read_ability = ReadAbility.new
# read_ability.can? :edit, User.new #=> false
# read_ability.merge(WritingAbility.new)
# read_ability.can? :edit, User.new #=> true
# read_ability.aliased_actions #=> [:see => [:show, :index], :modify => [:create, :update]]
#
# If there are collisions when merging the +aliased_actions+, the actions on +self+ will be
# overwritten.
#
# class ReadAbility
# include CanCan::Ability
#
# def initialize
# alias_action :show, :index, to: :see
# end
# end
#
# class ShowAbility
# include CanCan::Ability
#
# def initialize
# alias_action :show, to: :see
# end
# end
#
# read_ability = ReadAbility.new
# read_ability.merge(ShowAbility)
# read_ability.aliased_actions #=> [:see => [:show]]
def merge(ability)
ability.rules.each do |rule|
add_rule(rule.dup)
end
@aliased_actions = aliased_actions.merge(ability.aliased_actions)
self
end
# Return a hash of permissions for the user in the format of:
# {
# can: can_hash,
# cannot: cannot_hash
# }
#
# Where can_hash and cannot_hash are formatted thusly:
# {
# action: { subject: [attributes] }
# }
def permissions
permissions_list = {
can: Hash.new { |actions, k1| actions[k1] = Hash.new { |subjects, k2| subjects[k2] = [] } },
cannot: Hash.new { |actions, k1| actions[k1] = Hash.new { |subjects, k2| subjects[k2] = [] } }
}
rules.each { |rule| extract_rule_in_permissions(permissions_list, rule) }
permissions_list
end
def extract_rule_in_permissions(permissions_list, rule)
expand_actions(rule.actions).each do |action|
container = rule.base_behavior ? :can : :cannot
rule.subjects.each do |subject|
permissions_list[container][action][subject.to_s] += rule.attributes
end
end
end
private
def unauthorized_message_keys(action, subject)
subject = (subject.class == Class ? subject : subject.class).name.underscore unless subject.is_a? Symbol
aliases = aliases_for_action(action)
[subject, :all].product([*aliases, :manage]).map do |try_subject, try_action|
:"#{try_action}.#{try_subject}"
end
end
# It translates to an array the subject or the hash with multiple subjects given to can?.
def extract_subjects(subject)
if subject.is_a?(Hash) && subject.key?(:any)
subject[:any]
else
[subject]
end
end
def alternative_subjects(subject)
subject = subject.class unless subject.is_a?(Module)
if subject.respond_to?(:subclasses) && defined?(ActiveRecord::Base) && subject < ActiveRecord::Base
[:all, *(subject.ancestors + subject.subclasses), subject.class.to_s]
else
[:all, *subject.ancestors, subject.class.to_s]
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_resource_name_finder.rb | lib/cancan/controller_resource_name_finder.rb | # frozen_string_literal: true
module CanCan
module ControllerResourceNameFinder
protected
def name_from_controller
@params[:controller].split('/').last.singularize
end
def namespaced_name
[namespace, name].join('/').singularize.camelize.safe_constantize || name
end
def name
@name || name_from_controller
end
def namespace
@params[:controller].split('/')[0..-2]
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/sti_detector.rb | lib/cancan/sti_detector.rb | # frozen_string_literal: true
class StiDetector
def self.sti_class?(subject)
return false unless defined?(ActiveRecord::Base)
return false unless subject.respond_to?(:descends_from_active_record?)
return false if subject == :all || subject.descends_from_active_record?
return false unless subject < ActiveRecord::Base
true
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_resource_loader.rb | lib/cancan/controller_resource_loader.rb | # frozen_string_literal: true
require_relative 'controller_resource_finder.rb'
require_relative 'controller_resource_name_finder.rb'
require_relative 'controller_resource_builder.rb'
require_relative 'controller_resource_sanitizer.rb'
module CanCan
module ControllerResourceLoader
include CanCan::ControllerResourceNameFinder
include CanCan::ControllerResourceFinder
include CanCan::ControllerResourceBuilder
include CanCan::ControllerResourceSanitizer
def load_resource
return if skip?(:load)
if load_instance?
self.resource_instance ||= load_resource_instance
elsif load_collection?
self.collection_instance ||= load_collection
end
end
protected
def new_actions
%i[new create] + Array(@options[:new])
end
def resource_params_by_key(key)
return unless @options[key] && @params.key?(extract_key(@options[key]))
@params[extract_key(@options[key])]
end
def resource_params_by_namespaced_name
resource_params_by_key(:instance_name) || resource_params_by_key(:class) || (
params = @params[extract_key(namespaced_name)]
params.respond_to?(:to_h) ? params : nil)
end
def resource_params
if parameters_require_sanitizing? && params_method.present?
sanitize_parameters
else
resource_params_by_namespaced_name
end
end
def fetch_parent(name)
if @controller.instance_variable_defined? "@#{name}"
@controller.instance_variable_get("@#{name}")
elsif @controller.respond_to?(name, true)
@controller.send(name)
end
end
# The object to load this resource through.
def parent_resource
parent_name && fetch_parent(parent_name)
end
def parent_name
@options[:through] && [@options[:through]].flatten.detect { |i| fetch_parent(i) }
end
def resource_base_through_parent_resource
if @options[:singleton]
resource_class
else
parent_resource.send(@options[:through_association] || name.to_s.pluralize)
end
end
def resource_base_through
if parent_resource
resource_base_through_parent_resource
elsif @options[:shallow]
resource_class
else
# maybe this should be a record not found error instead?
raise AccessDenied.new(nil, authorization_action, resource_class)
end
end
# The object that methods (such as "find", "new" or "build") are called on.
# If the :through option is passed it will go through an association on that instance.
# If the :shallow option is passed it will use the resource_class if there's no parent
# If the :singleton option is passed it won't use the association because it needs to be handled later.
def resource_base
@options[:through] ? resource_base_through : resource_class
end
def parent_authorization_action
@options[:parent_action] || :show
end
def authorization_action
parent? ? parent_authorization_action : @params[:action].to_sym
end
def load_collection
resource_base.accessible_by(current_ability, authorization_action)
end
def load_resource_instance
if !parent? && new_actions.include?(@params[:action].to_sym)
build_resource
elsif id_param || @options[:singleton]
find_resource
end
end
private
def extract_key(value)
value.to_s.underscore.tr('/', '_')
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_resource_sanitizer.rb | lib/cancan/controller_resource_sanitizer.rb | # frozen_string_literal: true
module CanCan
module ControllerResourceSanitizer
protected
def sanitize_parameters
case params_method
when Symbol
@controller.send(params_method)
when String
@controller.instance_eval(params_method)
when Proc
params_method.call(@controller)
end
end
def params_methods
methods = ["#{@params[:action]}_params".to_sym, "#{name}_params".to_sym, :resource_params]
methods.unshift(@options[:param_method]) if @options[:param_method].present?
methods
end
def params_method
params_methods.each do |method|
return method if (method.is_a?(Symbol) && @controller.respond_to?(method, true)) ||
method.is_a?(String) || method.is_a?(Proc)
end
nil
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_resource_builder.rb | lib/cancan/controller_resource_builder.rb | # frozen_string_literal: true
module CanCan
module ControllerResourceBuilder
protected
def build_resource
resource = resource_base.new(resource_params || {})
assign_attributes(resource)
end
def assign_attributes(resource)
resource.send("#{parent_name}=", parent_resource) if @options[:singleton] && parent_resource
initial_attributes.each do |attr_name, value|
resource.send("#{attr_name}=", value)
end
resource
end
def initial_attributes
current_ability.attributes_for(@params[:action].to_sym, resource_class).delete_if do |key, _value|
resource_params && resource_params.include?(key)
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/relevant.rb | lib/cancan/relevant.rb | # frozen_string_literal: true
module CanCan
module Relevant
# Matches both the action, subject, and attribute, not necessarily the conditions
def relevant?(action, subject)
subject = subject.values.first if subject.class == Hash
@match_all || (matches_action?(action) && matches_subject?(subject))
end
private
def matches_action?(action)
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
end
def matches_subject?(subject)
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
end
def matches_subject_class?(subject)
@subjects.any? do |sub|
sub.is_a?(Module) && (subject.is_a?(sub) ||
subject.class.to_s == sub.to_s ||
(subject.is_a?(Module) && subject.ancestors.include?(sub)))
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/class_matcher.rb | lib/cancan/class_matcher.rb | require_relative 'sti_detector'
# This class is responsible for matching classes and their subclasses as well as
# upmatching classes to their ancestors.
# This is used to generate sti connections
class SubjectClassMatcher
def self.matches_subject_class?(subjects, subject)
subjects.any? do |sub|
has_subclasses = subject.respond_to?(:subclasses)
matching_class_check(subject, sub, has_subclasses)
end
end
def self.matching_class_check(subject, sub, has_subclasses)
matches = matches_class_or_is_related(subject, sub)
if has_subclasses
return matches unless StiDetector.sti_class?(sub)
matches || subject.subclasses.include?(sub)
else
matches
end
end
def self.matches_class_or_is_related(subject, sub)
sub.is_a?(Module) && (subject.is_a?(sub) ||
subject.class.to_s == sub.to_s ||
(subject.is_a?(Module) && subject.ancestors.include?(sub)))
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/parameter_validators.rb | lib/cancan/parameter_validators.rb | # frozen_string_literal: true
module CanCan
module ParameterValidators
def valid_attribute_param?(attribute)
attribute.nil? || attribute.is_a?(Symbol) || (attribute.is_a?(Array) && attribute.all? { |a| a.is_a?(Symbol) })
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_resource.rb | lib/cancan/controller_resource.rb | # frozen_string_literal: true
require_relative 'controller_resource_loader.rb'
module CanCan
# Handle the load and authorization controller logic
# so we don't clutter up all controllers with non-interface methods.
# This class is used internally, so you do not need to call methods directly on it.
class ControllerResource # :nodoc:
include ControllerResourceLoader
def self.add_before_action(controller_class, method, *args)
options = args.extract_options!
resource_name = args.first
before_action_method = before_callback_name(options)
controller_class.send(before_action_method, options.slice(:only, :except, :if, :unless)) do |controller|
controller.class.cancan_resource_class
.new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method)
end
end
def self.before_callback_name(options)
options.delete(:prepend) ? :prepend_before_action : :before_action
end
def initialize(controller, *args)
@controller = controller
@params = controller.params
@options = args.extract_options!
@name = args.first
end
def load_and_authorize_resource
load_resource
authorize_resource
end
def authorize_resource
return if skip?(:authorize)
@controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
end
def parent?
@options.key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
end
def skip?(behavior)
return false unless (options = @controller.class.cancan_skipper[behavior][@name])
options == {} ||
options[:except] && !action_exists_in?(options[:except]) ||
action_exists_in?(options[:only])
end
protected
# Returns the class used for this resource. This can be overridden by the :class option.
# If +false+ is passed in it will use the resource name as a symbol in which case it should
# only be used for authorization, not loading since there's no class to load through.
def resource_class
case @options[:class]
when false
name.to_sym
when nil
namespaced_name.to_s.camelize.constantize
when String
@options[:class].constantize
else
@options[:class]
end
end
def load_instance?
parent? || member_action?
end
def load_collection?
resource_base.respond_to?(:accessible_by) && !current_ability.has_block?(authorization_action, resource_class)
end
def member_action?
new_actions.include?(@params[:action].to_sym) || @options[:singleton] ||
((@params[:id] || @params[@options[:id_param]]) &&
!collection_actions.include?(@params[:action].to_sym))
end
def resource_class_with_parent
parent_resource ? { parent_resource => resource_class } : resource_class
end
def resource_instance=(instance)
@controller.instance_variable_set("@#{instance_name}", instance)
end
def resource_instance
return unless load_instance? && @controller.instance_variable_defined?("@#{instance_name}")
@controller.instance_variable_get("@#{instance_name}")
end
def collection_instance=(instance)
@controller.instance_variable_set("@#{instance_name.to_s.pluralize}", instance)
end
def collection_instance
return unless @controller.instance_variable_defined?("@#{instance_name.to_s.pluralize}")
@controller.instance_variable_get("@#{instance_name.to_s.pluralize}")
end
def parameters_require_sanitizing?
save_actions.include?(@params[:action].to_sym) || resource_params_by_namespaced_name.present?
end
def instance_name
@options[:instance_name] || name
end
def collection_actions
[:index] + Array(@options[:collection])
end
def save_actions
%i[create update]
end
private
def action_exists_in?(options)
Array(options).include?(@params[:action].to_sym)
end
def adapter
ModelAdapters::AbstractAdapter.adapter_class(resource_class)
end
def current_ability
@controller.send(:current_ability)
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/rule.rb | lib/cancan/rule.rb | # frozen_string_literal: true
require_relative 'conditions_matcher.rb'
require_relative 'class_matcher.rb'
require_relative 'relevant.rb'
module CanCan
# This class is used internally and should only be called through Ability.
# it holds the information about a "can" call made on Ability and provides
# helpful methods to determine permission checking and conditions hash generation.
class Rule # :nodoc:
include ConditionsMatcher
include Relevant
include ParameterValidators
attr_reader :base_behavior, :subjects, :actions, :conditions, :attributes, :block
attr_writer :expanded_actions, :conditions
# The first argument when initializing is the base_behavior which is a true/false
# value. True for "can" and false for "cannot". The next two arguments are the action
# and subject respectively (such as :read, @project). The third argument is a hash
# of conditions and the last one is the block passed to the "can" call.
def initialize(base_behavior, action, subject, *extra_args, &block)
# for backwards compatibility, attributes are an optional parameter. Check if
# attributes were passed or are actually conditions
attributes, extra_args = parse_attributes_from_extra_args(extra_args)
condition_and_block_check(extra_args, block, action, subject)
@match_all = action.nil? && subject.nil?
raise Error, "Subject is required for #{action}" if action && subject.nil?
@base_behavior = base_behavior
@actions = wrap(action)
@subjects = wrap(subject)
@attributes = wrap(attributes)
@conditions = extra_args || {}
@block = block
end
def inspect
repr = "#<#{self.class.name}"
repr += "#{@base_behavior ? 'can' : 'cannot'} #{@actions.inspect}, #{@subjects.inspect}, #{@attributes.inspect}"
if with_scope?
repr += ", #{@conditions.where_values_hash}"
elsif [Hash, String].include?(@conditions.class)
repr += ", #{@conditions.inspect}"
end
repr + '>'
end
def can_rule?
base_behavior
end
def cannot_catch_all?
!can_rule? && catch_all?
end
def catch_all?
(with_scope? && @conditions.where_values_hash.empty?) ||
(!with_scope? && [nil, false, [], {}, '', ' '].include?(@conditions))
end
def only_block?
conditions_empty? && @block
end
def only_raw_sql?
@block.nil? && !conditions_empty? && !@conditions.is_a?(Hash)
end
def with_scope?
defined?(ActiveRecord) && @conditions.is_a?(ActiveRecord::Relation)
end
def associations_hash(conditions = @conditions)
hash = {}
if conditions.is_a? Hash
conditions.map do |name, value|
hash[name] = associations_hash(value) if value.is_a? Hash
end
end
hash
end
def attributes_from_conditions
attributes = {}
if @conditions.is_a? Hash
@conditions.each do |key, value|
attributes[key] = value unless [Array, Range, Hash].include? value.class
end
end
attributes
end
def matches_attributes?(attribute)
return true if @attributes.empty?
return @base_behavior if attribute.nil?
@attributes.include?(attribute.to_sym)
end
private
def matches_action?(action)
@expanded_actions.include?(:manage) || @expanded_actions.include?(action)
end
def matches_subject?(subject)
@subjects.include?(:all) || @subjects.include?(subject) || matches_subject_class?(subject)
end
def matches_subject_class?(subject)
SubjectClassMatcher.matches_subject_class?(@subjects, subject)
end
def parse_attributes_from_extra_args(args)
attributes = args.shift if valid_attribute_param?(args.first)
extra_args = args.shift
[attributes, extra_args]
end
def condition_and_block_check(conditions, block, action, subject)
return unless conditions.is_a?(Hash) && block
raise BlockAndConditionsError, 'A hash of conditions is mutually exclusive with a block. ' \
"Check \":#{action} #{subject}\" ability."
end
def wrap(object)
if object.nil?
[]
elsif object.respond_to?(:to_ary)
object.to_ary || [object]
else
[object]
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/config.rb | lib/cancan/config.rb | # frozen_string_literal: true
module CanCan
def self.valid_accessible_by_strategies
strategies = [:left_join]
unless does_not_support_subquery_strategy?
strategies.push(:joined_alias_exists_subquery, :joined_alias_each_rule_as_exists_subquery, :subquery)
end
strategies
end
# You can disable the rules compressor if it's causing unexpected issues.
def self.rules_compressor_enabled
return @rules_compressor_enabled if defined?(@rules_compressor_enabled)
@rules_compressor_enabled = true
end
def self.rules_compressor_enabled=(value)
@rules_compressor_enabled = value
end
def self.with_rules_compressor_enabled(value)
return yield if value == rules_compressor_enabled
begin
rules_compressor_enabled_was = rules_compressor_enabled
@rules_compressor_enabled = value
yield
ensure
@rules_compressor_enabled = rules_compressor_enabled_was
end
end
# Determines how CanCan should build queries when calling accessible_by,
# if the query will contain a join. The default strategy is `:subquery`.
#
# # config/initializers/cancan.rb
# CanCan.accessible_by_strategy = :subquery
#
# Valid strategies are:
# - :subquery - Creates a nested query with all joins, wrapped by a
# WHERE IN query.
# - :left_join - Calls the joins directly using `left_joins`, and
# ensures records are unique using `distinct`. Note that
# `distinct` is not reliable in some cases. See
# https://github.com/CanCanCommunity/cancancan/pull/605
def self.accessible_by_strategy
return @accessible_by_strategy if @accessible_by_strategy
@accessible_by_strategy = default_accessible_by_strategy
end
def self.default_accessible_by_strategy
if does_not_support_subquery_strategy?
# see https://github.com/CanCanCommunity/cancancan/pull/655 for where this was added
# the `subquery` strategy (from https://github.com/CanCanCommunity/cancancan/pull/619
# only works in Rails 5 and higher
:left_join
else
:subquery
end
end
def self.accessible_by_strategy=(value)
validate_accessible_by_strategy!(value)
if value == :subquery && does_not_support_subquery_strategy?
raise ArgumentError, 'accessible_by_strategy = :subquery requires ActiveRecord 5 or newer'
end
@accessible_by_strategy = value
end
def self.with_accessible_by_strategy(value)
return yield if value == accessible_by_strategy
validate_accessible_by_strategy!(value)
begin
strategy_was = accessible_by_strategy
@accessible_by_strategy = value
yield
ensure
@accessible_by_strategy = strategy_was
end
end
def self.validate_accessible_by_strategy!(value)
return if valid_accessible_by_strategies.include?(value)
raise ArgumentError, "accessible_by_strategy must be one of #{valid_accessible_by_strategies.join(', ')}"
end
def self.does_not_support_subquery_strategy?
!defined?(CanCan::ModelAdapters::ActiveRecordAdapter) ||
CanCan::ModelAdapters::ActiveRecordAdapter.version_lower?('5.0.0')
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_additions.rb | lib/cancan/controller_additions.rb | # frozen_string_literal: true
module CanCan
# This module is automatically included into all controllers.
# It also makes the "can?" and "cannot?" methods available to all views.
module ControllerAdditions
module ClassMethods
# Sets up a before filter which loads and authorizes the current resource. This performs both
# load_resource and authorize_resource and accepts the same arguments. See those methods for details.
#
# class BooksController < ApplicationController
# load_and_authorize_resource
# end
#
def load_and_authorize_resource(*args)
cancan_resource_class.add_before_action(self, :load_and_authorize_resource, *args)
end
# Sets up a before filter which loads the model resource into an instance variable.
# For example, given an ArticlesController it will load the current article into the @article
# instance variable. It does this by either calling Article.find(params[:id]) or
# Article.new(params[:article]) depending upon the action. The index action will
# automatically set @articles to Article.accessible_by(current_ability).
#
# If a conditions hash is used in the Ability, the +new+ and +create+ actions will set
# the initial attributes based on these conditions. This way these actions will satisfy
# the ability restrictions.
#
# Call this method directly on the controller class.
#
# class BooksController < ApplicationController
# load_resource
# end
#
# A resource is not loaded if the instance variable is already set. This makes it easy to override
# the behavior through a before_action on certain actions.
#
# class BooksController < ApplicationController
# before_action :find_book_by_permalink, :only => :show
# load_resource
#
# private
#
# def find_book_by_permalink
# @book = Book.find_by_permalink!(params[:id])
# end
# end
#
# If a name is provided which does not match the controller it assumes it is a parent resource. Child
# resources can then be loaded through it.
#
# class BooksController < ApplicationController
# load_resource :author
# load_resource :book, :through => :author
# end
#
# Here the author resource will be loaded before each action using params[:author_id]. The book resource
# will then be loaded through the @author instance variable.
#
# That first argument is optional and will default to the singular name of the controller.
# A hash of options (see below) can also be passed to this method to further customize it.
#
# See load_and_authorize_resource to automatically authorize the resource too.
#
# Options:
# [:+only+]
# Only applies before filter to given actions.
#
# [:+except+]
# Does not apply before filter to given actions.
#
# [:+through+]
# Load this resource through another one. This should match the name of the parent instance variable or method.
#
# [:+through_association+]
# The name of the association to fetch the child records through the parent resource.
# This is normally not needed because it defaults to the pluralized resource name.
#
# [:+shallow+]
# Pass +true+ to allow this resource to be loaded directly when parent is +nil+. Defaults to +false+.
#
# [:+singleton+]
# Pass +true+ if this is a singleton resource through a +has_one+ association.
#
# [:+parent+]
# True or false depending on if the resource is considered a parent resource.
# This defaults to +true+ if a resource name is given which does not match the controller.
#
# [:+class+]
# The class to use for the model (string or constant).
#
# [:+instance_name+]
# The name of the instance variable to load the resource into.
#
# [:+find_by+]
# Find using a different attribute other than id. For example.
#
# load_resource :find_by => :permalink # will use find_by_permalink!(params[:id])
#
# [:+id_param+]
# Find using a param key other than :id. For example:
#
# load_resource :id_param => :url # will use find(params[:url])
#
# [:+collection+]
# Specify which actions are resource collection actions in addition to :+index+. This
# is usually not necessary because it will try to guess depending on if the id param is present.
#
# load_resource :collection => [:sort, :list]
#
# [:+new+]
# Specify which actions are new resource actions in addition to :+new+ and :+create+.
# Pass an action name into here if you would like to build a new resource instead of
# fetch one.
#
# load_resource :new => :build
#
# [:+prepend+]
# Passing +true+ will use prepend_before_action instead of a normal before_action.
#
def load_resource(*args)
cancan_resource_class.add_before_action(self, :load_resource, *args)
end
# Sets up a before filter which authorizes the resource using the instance variable.
# For example, if you have an ArticlesController it will check the @article instance variable
# and ensure the user can perform the current action on it. Under the hood it is doing
# something like the following.
#
# authorize!(params[:action].to_sym, @article || Article)
#
# Call this method directly on the controller class.
#
# class BooksController < ApplicationController
# authorize_resource
# end
#
# If you pass in the name of a resource which does not match the controller it will assume
# it is a parent resource.
#
# class BooksController < ApplicationController
# authorize_resource :author
# authorize_resource :book
# end
#
# Here it will authorize :+show+, @+author+ on every action before authorizing the book.
#
# That first argument is optional and will default to the singular name of the controller.
# A hash of options (see below) can also be passed to this method to further customize it.
#
# See load_and_authorize_resource to automatically load the resource too.
#
# Options:
# [:+only+]
# Only applies before filter to given actions.
#
# [:+except+]
# Does not apply before filter to given actions.
#
# [:+singleton+]
# Pass +true+ if this is a singleton resource through a +has_one+ association.
#
# [:+parent+]
# True or false depending on if the resource is considered a parent resource.
# This defaults to +true+ if a resource name is given which does not match the controller.
#
# [:+class+]
# The class to use for the model (string or constant). This passed in when the instance variable is not set.
# Pass +false+ if there is no associated class for this resource and it will use a symbol of the resource name.
#
# [:+instance_name+]
# The name of the instance variable for this resource.
#
# [:+id_param+]
# Find using a param key other than :id. For example:
#
# load_resource :id_param => :url # will use find(params[:url])
#
# [:+through+]
# Authorize conditions on this parent resource when instance isn't available.
#
# [:+prepend+]
# Passing +true+ will use prepend_before_action instead of a normal before_action.
#
def authorize_resource(*args)
cancan_resource_class.add_before_action(self, :authorize_resource, *args)
end
# Skip both the loading and authorization behavior of CanCan for this given controller. This is primarily
# useful to skip the behavior of a superclass. You can pass :only and :except options to specify which actions
# to skip the effects on. It will apply to all actions by default.
#
# class ProjectsController < SomeOtherController
# skip_load_and_authorize_resource :only => :index
# end
#
# You can also pass the resource name as the first argument to skip that resource.
def skip_load_and_authorize_resource(*args)
skip_load_resource(*args)
skip_authorize_resource(*args)
end
# Skip the loading behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
# only do authorization on certain actions. You can pass :only and :except options to specify which actions to
# skip the effects on. It will apply to all actions by default.
#
# class ProjectsController < ApplicationController
# load_and_authorize_resource
# skip_load_resource :only => :index
# end
#
# You can also pass the resource name as the first argument to skip that resource.
def skip_load_resource(*args)
options = args.extract_options!
name = args.first
cancan_skipper[:load][name] = options
end
# Skip the authorization behavior of CanCan. This is useful when using +load_and_authorize_resource+ but want to
# only do loading on certain actions. You can pass :only and :except options to specify which actions to
# skip the effects on. It will apply to all actions by default.
#
# class ProjectsController < ApplicationController
# load_and_authorize_resource
# skip_authorize_resource :only => :index
# end
#
# You can also pass the resource name as the first argument to skip that resource.
def skip_authorize_resource(*args)
options = args.extract_options!
name = args.first
cancan_skipper[:authorize][name] = options
end
# Add this to a controller to ensure it performs authorization through +authorize+! or +authorize_resource+ call.
# If neither of these authorization methods are called,
# a CanCan::AuthorizationNotPerformed exception will be raised.
# This is normally added to the ApplicationController to ensure all controller actions do authorization.
#
# class ApplicationController < ActionController::Base
# check_authorization
# end
#
# See skip_authorization_check to bypass this check on specific controller actions.
#
# Options:
# [:+only+]
# Only applies to given actions.
#
# [:+except+]
# Does not apply to given actions.
#
# [:+if+]
# Supply the name of a controller method to be called.
# The authorization check only takes place if this returns true.
#
# check_authorization :if => :admin_controller?
#
# [:+unless+]
# Supply the name of a controller method to be called.
# The authorization check only takes place if this returns false.
#
# check_authorization :unless => :devise_controller?
#
def check_authorization(options = {})
block = proc do |controller|
next if controller.instance_variable_defined?(:@_authorized)
next if options[:if] && !controller.send(options[:if])
next if options[:unless] && controller.send(options[:unless])
raise AuthorizationNotPerformed,
'This action failed the check_authorization because it does not authorize_resource. ' \
'Add skip_authorization_check to bypass this check.'
end
send(:after_action, options.slice(:only, :except), &block)
end
# Call this in the class of a controller to skip the check_authorization behavior on the actions.
#
# class HomeController < ApplicationController
# skip_authorization_check :only => :index
# end
#
# Any arguments are passed to the +before_action+ it triggers.
def skip_authorization_check(*args)
block = proc { |controller| controller.instance_variable_set(:@_authorized, true) }
send(:before_action, *args, &block)
end
def cancan_resource_class
ControllerResource
end
def cancan_skipper
self._cancan_skipper ||= { authorize: {}, load: {} }
end
end
def self.included(base)
base.extend ClassMethods
base.helper_method :can?, :cannot?, :current_ability if base.respond_to? :helper_method
base.class_attribute :_cancan_skipper
end
# Raises a CanCan::AccessDenied exception if the current_ability cannot
# perform the given action. This is usually called in a controller action or
# before filter to perform the authorization.
#
# def show
# @article = Article.find(params[:id])
# authorize! :read, @article
# end
#
# A :message option can be passed to specify a different message.
#
# authorize! :read, @article, :message => "Not authorized to read #{@article.name}"
#
# You can also use I18n to customize the message. Action aliases defined in Ability work here.
#
# en:
# unauthorized:
# manage:
# all: "Not authorized to %{action} %{subject}."
# user: "Not allowed to manage other user accounts."
# update:
# project: "Not allowed to update this project."
#
# You can rescue from the exception in the controller to customize how unauthorized
# access is displayed to the user.
#
# class ApplicationController < ActionController::Base
# rescue_from CanCan::AccessDenied do |exception|
# redirect_to root_url, :alert => exception.message
# end
# end
#
# See the CanCan::AccessDenied exception for more details on working with the exception.
#
# See the load_and_authorize_resource method to automatically add the authorize! behavior
# to the default RESTful actions.
def authorize!(*args)
@_authorized = true
current_ability.authorize!(*args)
end
# Creates and returns the current user's ability and caches it. If you
# want to override how the Ability is defined then this is the place.
# Just define the method in the controller to change behavior.
#
# def current_ability
# # instead of Ability.new(current_user)
# @current_ability ||= UserAbility.new(current_account)
# end
#
# Notice it is important to cache the ability object so it is not
# recreated every time.
def current_ability
@current_ability ||= ::Ability.new(current_user)
end
# Use in the controller or view to check the user's permission for a given action
# and object.
#
# can? :destroy, @project
#
# You can also pass the class instead of an instance (if you don't have one handy).
#
# <% if can? :create, Project %>
# <%= link_to "New Project", new_project_path %>
# <% end %>
#
# If it's a nested resource, you can pass the parent instance in a hash. This way it will
# check conditions which reach through that association.
#
# <% if can? :create, @category => Project %>
# <%= link_to "New Project", new_project_path %>
# <% end %>
#
# This simply calls "can?" on the current_ability. See Ability#can?.
def can?(*args)
current_ability.can?(*args)
end
# Convenience method which works the same as "can?" but returns the opposite value.
#
# cannot? :destroy, @project
#
def cannot?(*args)
current_ability.cannot?(*args)
end
end
end
if defined? ActiveSupport
ActiveSupport.on_load(:action_controller) do
include CanCan::ControllerAdditions
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/controller_resource_finder.rb | lib/cancan/controller_resource_finder.rb | # frozen_string_literal: true
module CanCan
module ControllerResourceFinder
protected
def find_resource
if @options[:singleton] && parent_resource.respond_to?(name)
parent_resource.send(name)
elsif @options[:find_by]
find_resource_using_find_by
else
adapter.find(resource_base, id_param)
end
end
def find_resource_using_find_by
find_by_dynamic_finder || find_by_find_by_finder || resource_base.send(@options[:find_by], id_param)
end
def find_by_dynamic_finder
method_name = "find_by_#{@options[:find_by]}!"
resource_base.send(method_name, id_param) if resource_base.respond_to? method_name
end
def find_by_find_by_finder
resource_base.find_by(@options[:find_by].to_sym => id_param) if resource_base.respond_to? :find_by
end
def id_param
@params[id_param_key].to_s if @params[id_param_key].present?
end
def id_param_key
if @options[:id_param]
@options[:id_param]
else
parent? ? :"#{name}_id" : :id
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/rules_compressor.rb | lib/cancan/rules_compressor.rb | # frozen_string_literal: true
require_relative 'conditions_matcher.rb'
module CanCan
class RulesCompressor
attr_reader :initial_rules, :rules_collapsed
def initialize(rules)
@initial_rules = rules
@rules_collapsed = compress(@initial_rules)
end
def compress(array)
array = simplify(array)
idx = array.rindex(&:catch_all?)
return array unless idx
value = array[idx]
array[idx..-1]
.drop_while { |n| n.base_behavior == value.base_behavior }
.tap { |a| a.unshift(value) unless value.cannot_catch_all? }
end
# If we have A OR (!A AND anything ), then we can simplify to A OR anything
# If we have A OR (A OR anything ), then we can simplify to A OR anything
# If we have !A AND (A OR something), then we can simplify it to !A AND something
# If we have !A AND (!A AND something), then we can simplify it to !A AND something
#
# So as soon as we see a condition that is the same as the previous one,
# we can skip it, no matter of the base_behavior
def simplify(rules)
seen = Set.new
rules.reverse_each.filter_map do |rule|
next if seen.include?(rule.conditions)
seen.add(rule.conditions)
rule
end.reverse
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/unauthorized_message_resolver.rb | lib/cancan/unauthorized_message_resolver.rb | # frozen_string_literal: true
module CanCan
module UnauthorizedMessageResolver
def unauthorized_message(action, subject)
subject = subject.values.last if subject.is_a?(Hash)
keys = unauthorized_message_keys(action, subject)
variables = {}
variables[:action] = I18n.translate("actions.#{action}", default: action.to_s)
variables[:subject] = translate_subject(subject)
message = I18n.translate(keys.shift, **variables.merge(scope: :unauthorized, default: keys + ['']))
message.blank? ? nil : message
end
def translate_subject(subject)
klass = (subject.class == Class ? subject : subject.class)
if klass.respond_to?(:model_name)
klass.model_name.human
else
klass.to_s.underscore.humanize.downcase
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/conditions_matcher.rb | lib/cancan/conditions_matcher.rb | # frozen_string_literal: true
module CanCan
module ConditionsMatcher
# Matches the block or conditions hash
def matches_conditions?(action, subject, attribute = nil, *extra_args)
return call_block_with_all(action, subject, extra_args) if @match_all
return matches_block_conditions(subject, attribute, *extra_args) if @block
return matches_non_block_conditions(subject) unless conditions_empty?
true
end
private
def subject_class?(subject)
klass = (subject.is_a?(Hash) ? subject.values.first : subject).class
[Class, Module].include? klass
end
def matches_block_conditions(subject, attribute, *extra_args)
return @base_behavior if subject_class?(subject)
if attribute
@block.call(subject, attribute, *extra_args)
else
@block.call(subject, *extra_args)
end
end
def matches_non_block_conditions(subject)
return nested_subject_matches_conditions?(subject) if subject.class == Hash
return matches_conditions_hash?(subject) unless subject_class?(subject)
# Don't stop at "cannot" definitions when there are conditions.
@base_behavior
end
def nested_subject_matches_conditions?(subject_hash)
parent, child = subject_hash.first
adapter = model_adapter(parent)
parent_condition_name = adapter.parent_condition_name(parent, child)
matches_base_parent_conditions = matches_conditions_hash?(parent,
@conditions[parent_condition_name] || {})
matches_base_parent_conditions &&
(!adapter.override_nested_subject_conditions_matching?(parent, child, @conditions) ||
adapter.nested_subject_matches_conditions?(parent, child, @conditions))
end
# Checks if the given subject matches the given conditions hash.
# This behavior can be overridden by a model adapter by defining two class methods:
# override_matching_for_conditions?(subject, conditions) and
# matches_conditions_hash?(subject, conditions)
def matches_conditions_hash?(subject, conditions = @conditions)
return true if conditions.is_a?(Hash) && conditions.empty?
adapter = model_adapter(subject)
if adapter.override_conditions_hash_matching?(subject, conditions)
return adapter.matches_conditions_hash?(subject, conditions)
end
matches_all_conditions?(adapter, subject, conditions)
end
def matches_all_conditions?(adapter, subject, conditions)
if conditions.is_a?(Hash)
matches_hash_conditions?(adapter, subject, conditions)
elsif conditions.respond_to?(:include?)
conditions.include?(subject)
else
subject == conditions
end
end
def matches_hash_conditions?(adapter, subject, conditions)
conditions.all? do |name, value|
if adapter.override_condition_matching?(subject, name, value)
adapter.matches_condition?(subject, name, value)
else
condition_match?(subject.send(name), value)
end
end
end
def condition_match?(attribute, value)
case value
when Hash
hash_condition_match?(attribute, value)
when Range
value.cover?(attribute)
when Enumerable
value.include?(attribute)
else
attribute == value
end
end
def hash_condition_match?(attribute, value)
if attribute.is_a?(Array) || (defined?(ActiveRecord) && attribute.is_a?(ActiveRecord::Relation))
array_like_matches_condition_hash?(attribute, value)
else
attribute && matches_conditions_hash?(attribute, value)
end
end
def array_like_matches_condition_hash?(attribute, value)
if attribute.any?
attribute.any? { |element| matches_conditions_hash?(element, value) }
else
# you can use `nil`s in your ability definition to tell cancancan to find
# objects that *don't* have any children in a has_many relationship.
#
# for example, given ability:
# => can :read, Article, comments: { id: nil }
# cancancan will return articles where `article.comments == []`
#
# this is implemented here. `attribute` is `article.comments`, and it's an empty array.
# the expression below returns true if this was expected.
!value.values.empty? && value.values.all?(&:nil?)
end
end
def call_block_with_all(action, subject, *extra_args)
if subject.class == Class
@block.call(action, subject, nil, *extra_args)
else
@block.call(action, subject.class, subject, *extra_args)
end
end
def model_adapter(subject)
CanCan::ModelAdapters::AbstractAdapter.adapter_class(subject_class?(subject) ? subject : subject.class)
end
def conditions_empty?
# @conditions might be an ActiveRecord::Associations::CollectionProxy
# which it's `==` implementation will fetch all records for comparison
(@conditions.is_a?(Hash) && @conditions == {}) || @conditions.nil?
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/ability/actions.rb | lib/cancan/ability/actions.rb | # frozen_string_literal: true
module CanCan
module Ability
module Actions
# Alias one or more actions into another one.
#
# alias_action :update, :destroy, :to => :modify
# can :modify, Comment
#
# Then :modify permission will apply to both :update and :destroy requests.
#
# can? :update, Comment # => true
# can? :destroy, Comment # => true
#
# This only works in one direction. Passing the aliased action into the "can?" call
# will not work because aliases are meant to generate more generic actions.
#
# alias_action :update, :destroy, :to => :modify
# can :update, Comment
# can? :modify, Comment # => false
#
# Unless that exact alias is used.
#
# can :modify, Comment
# can? :modify, Comment # => true
#
# The following aliases are added by default for conveniently mapping common controller actions.
#
# alias_action :index, :show, :to => :read
# alias_action :new, :to => :create
# alias_action :edit, :to => :update
#
# This way one can use params[:action] in the controller to determine the permission.
def alias_action(*args)
target = args.pop[:to]
validate_target(target)
aliased_actions[target] ||= []
aliased_actions[target] += args
end
# Returns a hash of aliased actions. The key is the target and the value is an array of actions aliasing the key.
def aliased_actions
@aliased_actions ||= default_alias_actions
end
# Removes previously aliased actions including the defaults.
def clear_aliased_actions
@aliased_actions = {}
end
private
def default_alias_actions
{
read: %i[index show],
create: [:new],
update: [:edit]
}
end
# Given an action, it will try to find all of the actions which are aliased to it.
# This does the opposite kind of lookup as expand_actions.
def aliases_for_action(action)
results = [action]
aliased_actions.each do |aliased_action, actions|
results += aliases_for_action(aliased_action) if actions.include? action
end
results
end
def expanded_actions
@expanded_actions ||= {}
end
# Accepts an array of actions and returns an array of actions which match.
# This should be called before "matches?" and other checking methods since they
# rely on the actions to be expanded.
def expand_actions(actions)
expanded_actions[actions] ||= begin
expanded = []
actions.each do |action|
expanded << action
if (aliases = aliased_actions[action])
expanded += expand_actions(aliases)
end
end
expanded
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/ability/strong_parameter_support.rb | lib/cancan/ability/strong_parameter_support.rb | # frozen_string_literal: true
module CanCan
module Ability
module StrongParameterSupport
# Returns an array of attributes suitable for use with strong parameters
#
# Note: reversing the relevant rules is important. Normal order means that 'cannot'
# rules will come before 'can' rules. However, you can't remove attributes before
# they are added. The 'reverse' is so that attributes will be added before the
# 'cannot' rules remove them.
def permitted_attributes(action, subject)
relevant_rules(action, subject)
.reverse
.select { |rule| rule.matches_conditions? action, subject }
.each_with_object(Set.new) do |rule, set|
attributes = get_attributes(rule, subject)
# add attributes for 'can', remove them for 'cannot'
rule.base_behavior ? set.merge(attributes) : set.subtract(attributes)
end.to_a
end
private
def subject_class?(subject)
klass = (subject.is_a?(Hash) ? subject.values.first : subject).class
[Class, Module].include? klass
end
def get_attributes(rule, subject)
klass = subject_class?(subject) ? subject : subject.class
# empty attributes is an 'all'
if rule.attributes.empty? && klass < ActiveRecord::Base
klass.attribute_names.map(&:to_sym) - Array(klass.primary_key)
else
rule.attributes
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/ability/rules.rb | lib/cancan/ability/rules.rb | # frozen_string_literal: true
module CanCan
module Ability
module Rules
protected
# Must be protected as an ability can merge with other abilities.
# This means that an ability must expose their rules with another ability.
def rules
@rules ||= []
end
private
def add_rule(rule)
rules << rule
add_rule_to_index(rule, rules.size - 1)
end
def add_rule_to_index(rule, position)
@rules_index ||= {}
subjects = rule.subjects.compact
subjects << :all if subjects.empty?
subjects.each do |subject|
@rules_index[subject] ||= []
@rules_index[subject] << position
end
end
# Returns an array of Rule instances which match the action and subject
# This does not take into consideration any hash conditions or block statements
def relevant_rules(action, subject)
return [] unless @rules
relevant = possible_relevant_rules(subject).select do |rule|
rule.expanded_actions = expand_actions(rule.actions)
rule.relevant? action, subject
end
relevant.reverse!.uniq!
optimize_order! relevant
relevant
end
def possible_relevant_rules(subject)
if subject.is_a?(Hash)
rules
else
positions = @rules_index.values_at(subject, *alternative_subjects(subject))
positions.compact!
positions.flatten!
positions.sort!
positions.map { |i| @rules[i] }
end
end
def relevant_rules_for_match(action, subject)
relevant_rules(action, subject).each do |rule|
next unless rule.only_raw_sql?
raise Error,
"The can? and cannot? call cannot be used with a raw sql 'can' definition. " \
"The checking code cannot be determined for #{action.inspect} #{subject.inspect}"
end
end
def relevant_rules_for_query(action, subject)
rules = relevant_rules(action, subject).reject do |rule|
# reject 'cannot' rules with attributes when doing queries
rule.base_behavior == false && rule.attributes.present?
end
if rules.any?(&:only_block?)
raise Error, "The accessible_by call cannot be used with a block 'can' definition." \
"The SQL cannot be determined for #{action.inspect} #{subject.inspect}"
end
rules
end
# Optimizes the order of the rules, so that rules with the :all subject are evaluated first.
def optimize_order!(rules)
first_can_in_group = -1
rules.each_with_index do |rule, i|
(first_can_in_group = -1) && next unless rule.base_behavior
(first_can_in_group = i) && next if first_can_in_group == -1
next unless rule.subjects == [:all]
rules[i] = rules[first_can_in_group]
rules[first_can_in_group] = rule
first_can_in_group += 1
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/default_adapter.rb | lib/cancan/model_adapters/default_adapter.rb | # frozen_string_literal: true
module CanCan
module ModelAdapters
class DefaultAdapter < AbstractAdapter
# This adapter is used when no matching adapter is found
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/sti_normalizer.rb | lib/cancan/model_adapters/sti_normalizer.rb | require_relative '../sti_detector'
# this class is responsible for detecting sti classes and creating new rules for the
# relevant subclasses, using the inheritance_column as a merger
module CanCan
module ModelAdapters
class StiNormalizer
class << self
def normalize(rules)
rules_cache = []
return unless defined?(ActiveRecord::Base)
rules.delete_if do |rule|
subjects = rule.subjects.select do |subject|
update_rule(subject, rule, rules_cache)
end
subjects.length == rule.subjects.length
end
rules_cache.each { |rule| rules.push(rule) }
end
private
def update_rule(subject, rule, rules_cache)
return false unless StiDetector.sti_class?(subject)
rules_cache.push(build_rule_for_subclass(rule, subject))
true
end
# create a new rule for the subclasses that links on the inheritance_column
def build_rule_for_subclass(rule, subject)
sti_conditions = { subject.inheritance_column => subject.sti_name }
new_rule_conditions =
if rule.with_scope?
rule.conditions.where(sti_conditions)
else
rule.conditions.merge(sti_conditions)
end
CanCan::Rule.new(rule.base_behavior, rule.actions, subject.superclass,
new_rule_conditions, rule.block)
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/conditions_extractor.rb | lib/cancan/model_adapters/conditions_extractor.rb | # frozen_string_literal: true
# this class is responsible of converting the hash of conditions
# in "where conditions" to generate the sql query
# it consists of a names_cache that helps calculating the next name given to the association
# it tries to reflect the behavior of ActiveRecord when generating aliases for tables.
module CanCan
module ModelAdapters
class ConditionsExtractor
def initialize(model_class)
@names_cache = { model_class.table_name => [] }.with_indifferent_access
@root_model_class = model_class
end
def tableize_conditions(conditions, model_class = @root_model_class, path_to_key = 0)
return conditions unless conditions.is_a? Hash
conditions.each_with_object({}) do |(key, value), result_hash|
if value.is_a? Hash
result_hash.merge!(calculate_result_hash(key, model_class, path_to_key, result_hash, value))
else
result_hash[key] = value
end
result_hash
end
end
private
def calculate_result_hash(key, model_class, path_to_key, result_hash, value)
reflection = model_class.reflect_on_association(key)
nested_resulted = calculate_nested(model_class, result_hash, key, value.dup, path_to_key)
association_class = reflection.klass.name.constantize
tableize_conditions(nested_resulted, association_class, "#{path_to_key}_#{key}")
end
def calculate_nested(model_class, result_hash, relation_name, value, path_to_key)
value.each_with_object({}) do |(k, v), nested|
if v.is_a? Hash
value.delete(k)
nested[k] = v
else
table_alias = generate_table_alias(model_class, relation_name, path_to_key)
result_hash[table_alias] = value
end
nested
end
end
def generate_table_alias(model_class, relation_name, path_to_key)
table_alias = model_class.reflect_on_association(relation_name).table_name.to_sym
if already_used?(table_alias, relation_name, path_to_key)
table_alias = "#{relation_name.to_s.pluralize}_#{model_class.table_name}".to_sym
index = 1
while already_used?(table_alias, relation_name, path_to_key)
table_alias = "#{table_alias}_#{index += 1}".to_sym
end
end
add_to_cache(table_alias, relation_name, path_to_key)
end
def already_used?(table_alias, relation_name, path_to_key)
@names_cache[table_alias].try(:exclude?, "#{path_to_key}_#{relation_name}")
end
def add_to_cache(table_alias, relation_name, path_to_key)
@names_cache[table_alias] ||= []
@names_cache[table_alias] << "#{path_to_key}_#{relation_name}"
table_alias
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/active_record_adapter.rb | lib/cancan/model_adapters/active_record_adapter.rb | # frozen_string_literal: true
# rubocop:disable Metrics/AbcSize
# rubocop:disable Metrics/CyclomaticComplexity
# rubocop:disable Metrics/PerceivedComplexity
module CanCan
module ModelAdapters
class ActiveRecordAdapter < AbstractAdapter
def self.version_greater_or_equal?(version)
Gem::Version.new(ActiveRecord.version).release >= Gem::Version.new(version)
end
def self.version_lower?(version)
Gem::Version.new(ActiveRecord.version).release < Gem::Version.new(version)
end
attr_reader :compressed_rules
def initialize(model_class, rules)
super
@compressed_rules = if CanCan.rules_compressor_enabled
RulesCompressor.new(@rules.reverse).rules_collapsed.reverse
else
@rules
end
StiNormalizer.normalize(@compressed_rules)
ConditionsNormalizer.normalize(model_class, @compressed_rules)
end
class << self
# When belongs_to parent_id is a condition for a model,
# we want to check the parent when testing ability for a hash {parent => model}
def override_nested_subject_conditions_matching?(parent, child, all_conditions)
parent_child_conditions(parent, child, all_conditions).present?
end
# parent_id condition can be an array of integer or one integer, we check the parent against this
def nested_subject_matches_conditions?(parent, child, all_conditions)
id_condition = parent_child_conditions(parent, child, all_conditions)
return id_condition.include?(parent.id) if id_condition.is_a? Array
return id_condition == parent.id if id_condition.is_a? Integer
false
end
def parent_child_conditions(parent, child, all_conditions)
child_class = child.is_a?(Class) ? child : child.class
parent_class = parent.is_a?(Class) ? parent : parent.class
foreign_key = child_class.reflect_on_all_associations(:belongs_to).find do |association|
# Do not match on polymorphic associations or it will throw an error (klass cannot be determined)
!association.polymorphic? && association.klass == parent.class
end&.foreign_key&.to_sym
# Search again in case of polymorphic associations, this time matching on the :has_many side
# via the :as option, as well as klass
foreign_key ||= parent_class.reflect_on_all_associations(:has_many).find do |has_many_assoc|
matching_parent_child_polymorphic_association(has_many_assoc, child_class)
end&.foreign_key&.to_sym
foreign_key.nil? ? nil : all_conditions[foreign_key]
end
def matching_parent_child_polymorphic_association(parent_assoc, child_class)
return nil unless parent_assoc.klass == child_class
return nil if parent_assoc&.options[:as].nil?
child_class.reflect_on_all_associations(:belongs_to).find do |child_assoc|
# Only match this way for polymorphic associations
child_assoc.polymorphic? && child_assoc.name == parent_assoc.options[:as]
end
end
def child_association_to_parent(parent, child)
child_class = child.is_a?(Class) ? child : child.class
parent_class = parent.is_a?(Class) ? parent : parent.class
association = child_class.reflect_on_all_associations(:belongs_to).find do |belongs_to_assoc|
# Do not match on polymorphic associations or it will throw an error (klass cannot be determined)
!belongs_to_assoc.polymorphic? && belongs_to_assoc.klass == parent.class
end
return association if association
parent_class.reflect_on_all_associations(:has_many).each do |has_many_assoc|
association ||= matching_parent_child_polymorphic_association(has_many_assoc, child_class)
end
association
end
def parent_condition_name(parent, child)
child_association_to_parent(parent, child)&.name || parent.class.name.downcase.to_sym
end
end
# Returns conditions intended to be used inside a database query. Normally you will not call this
# method directly, but instead go through ModelAdditions#accessible_by.
#
# If there is only one "can" definition, a hash of conditions will be returned matching the one defined.
#
# can :manage, User, :id => 1
# query(:manage, User).conditions # => { :id => 1 }
#
# If there are multiple "can" definitions, a SQL string will be returned to handle complex cases.
#
# can :manage, User, :id => 1
# can :manage, User, :manager_id => 1
# cannot :manage, User, :self_managed => true
# query(:manage, User).conditions # => "not (self_managed = 't') AND ((manager_id = 1) OR (id = 1))"
#
def conditions
conditions_extractor = ConditionsExtractor.new(@model_class)
if @compressed_rules.size == 1 && @compressed_rules.first.base_behavior
# Return the conditions directly if there's just one definition
conditions_extractor.tableize_conditions(@compressed_rules.first.conditions).dup
else
extract_multiple_conditions(conditions_extractor, @compressed_rules)
end
end
def extract_multiple_conditions(conditions_extractor, rules)
rules.reverse.inject(false_sql) do |sql, rule|
merge_conditions(sql, conditions_extractor.tableize_conditions(rule.conditions).dup, rule.base_behavior)
end
end
def database_records
if override_scope
@model_class.where(nil).merge(override_scope)
elsif @model_class.respond_to?(:where) && @model_class.respond_to?(:joins)
build_relation(conditions)
else
@model_class.all(conditions: conditions, joins: joins)
end
end
def build_relation(*where_conditions)
relation = @model_class.where(*where_conditions)
return relation unless joins.present?
# subclasses must implement `build_joins_relation`
build_joins_relation(relation, *where_conditions)
end
# Returns the associations used in conditions for the :joins option of a search.
# See ModelAdditions#accessible_by
def joins
joins_hash = {}
@compressed_rules.reverse_each do |rule|
deep_merge(joins_hash, rule.associations_hash)
end
deep_clean(joins_hash) unless joins_hash.empty?
end
private
# Removes empty hashes and moves everything into arrays.
def deep_clean(joins_hash)
joins_hash.map { |name, nested| nested.empty? ? name : { name => deep_clean(nested) } }
end
# Takes two hashes and does a deep merge.
def deep_merge(base_hash, added_hash)
added_hash.each do |key, value|
if base_hash[key].is_a?(Hash)
deep_merge(base_hash[key], value) unless value.empty?
else
base_hash[key] = value
end
end
end
def override_scope
conditions = @compressed_rules.map(&:conditions).compact
return unless conditions.any? { |c| c.is_a?(ActiveRecord::Relation) }
return conditions.first if conditions.size == 1
raise_override_scope_error
end
def raise_override_scope_error
rule_found = @compressed_rules.detect { |rule| rule.conditions.is_a?(ActiveRecord::Relation) }
raise Error,
'Unable to merge an Active Record scope with other conditions. ' \
"Instead use a hash or SQL for #{rule_found.actions.first} #{rule_found.subjects.first} ability."
end
def merge_conditions(sql, conditions_hash, behavior)
if conditions_hash.blank?
behavior ? true_sql : false_sql
else
merge_non_empty_conditions(behavior, conditions_hash, sql)
end
end
def merge_non_empty_conditions(behavior, conditions_hash, sql)
conditions = sanitize_sql(conditions_hash)
case sql
when true_sql
behavior ? true_sql : "not (#{conditions})"
when false_sql
behavior ? conditions : false_sql
else
behavior ? "(#{conditions}) OR (#{sql})" : "not (#{conditions}) AND (#{sql})"
end
end
def false_sql
sanitize_sql(['?=?', true, false])
end
def true_sql
sanitize_sql(['?=?', true, true])
end
def sanitize_sql(conditions)
@model_class.send(:sanitize_sql, conditions)
end
end
end
end
# rubocop:enable Metrics/PerceivedComplexity
# rubocop:enable Metrics/CyclomaticComplexity
# rubocop:enable Metrics/AbcSize
ActiveSupport.on_load(:active_record) do
send :include, CanCan::ModelAdditions
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/conditions_normalizer.rb | lib/cancan/model_adapters/conditions_normalizer.rb | # this class is responsible of normalizing the hash of conditions
# by exploding has_many through associations
# when a condition is defined with an has_many through association this is exploded in all its parts
# TODO: it could identify STI and normalize it
module CanCan
module ModelAdapters
class ConditionsNormalizer
class << self
def normalize(model_class, rules)
rules.each { |rule| rule.conditions = normalize_conditions(model_class, rule.conditions) }
end
def normalize_conditions(model_class, conditions)
return conditions unless conditions.is_a? Hash
conditions.each_with_object({}) do |(key, value), result_hash|
if value.is_a? Hash
result_hash.merge!(calculate_result_hash(model_class, key, value))
else
result_hash[key] = value
end
result_hash
end
end
private
def calculate_result_hash(model_class, key, value)
reflection = model_class.reflect_on_association(key)
unless reflection
raise WrongAssociationName, "Association '#{key}' not defined in model '#{model_class.name}'"
end
if normalizable_association? reflection
key = reflection.options[:through]
value = { reflection.source_reflection_name => value }
reflection = model_class.reflect_on_association(key)
end
{ key => normalize_conditions(reflection.klass.name.constantize, value) }
end
def normalizable_association?(reflection)
reflection.options[:through].present? && !reflection.options[:source_type].present?
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/active_record_4_adapter.rb | lib/cancan/model_adapters/active_record_4_adapter.rb | # frozen_string_literal: true
module CanCan
module ModelAdapters
class ActiveRecord4Adapter < ActiveRecordAdapter
AbstractAdapter.inherited(self)
class << self
def for_class?(model_class)
version_lower?('5.0.0') && model_class <= ActiveRecord::Base
end
def override_condition_matching?(subject, name, _value)
subject.class.defined_enums.include?(name.to_s)
end
def matches_condition?(subject, name, value)
# Get the mapping from enum strings to values.
enum = subject.class.send(name.to_s.pluralize)
# Get the value of the attribute as an integer.
attribute = enum[subject.send(name)]
# Check to see if the value matches the condition.
if value.is_a?(Enumerable)
value.include? attribute
else
attribute == value
end
end
end
private
# As of rails 4, `includes()` no longer causes active record to
# look inside the where clause to decide to outer join tables
# you're using in the where. Instead, `references()` is required
# in addition to `includes()` to force the outer join.
def build_joins_relation(relation, *_where_conditions)
relation.includes(joins).references(joins)
end
# Rails 4.2 deprecates `sanitize_sql_hash_for_conditions`
def sanitize_sql(conditions)
if self.class.version_greater_or_equal?('4.2.0') && conditions.is_a?(Hash)
sanitize_sql_activerecord4(conditions)
else
@model_class.send(:sanitize_sql, conditions)
end
end
def sanitize_sql_activerecord4(conditions)
table = Arel::Table.new(@model_class.send(:table_name))
conditions = ActiveRecord::PredicateBuilder.resolve_column_aliases @model_class, conditions
conditions = @model_class.send(:expand_hash_conditions_for_aggregates, conditions)
ActiveRecord::PredicateBuilder.build_from_hash(@model_class, conditions, table).map do |b|
@model_class.send(:connection).visitor.compile b
end.join(' AND ')
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/active_record_5_adapter.rb | lib/cancan/model_adapters/active_record_5_adapter.rb | # frozen_string_literal: true
module CanCan
module ModelAdapters
class ActiveRecord5Adapter < ActiveRecord4Adapter
AbstractAdapter.inherited(self)
def self.for_class?(model_class)
version_greater_or_equal?('5.0.0') && model_class <= ActiveRecord::Base
end
# rails 5 is capable of using strings in enum
# but often people use symbols in rules
def self.matches_condition?(subject, name, value)
return super if Array.wrap(value).all? { |x| x.is_a? Integer }
attribute = subject.send(name)
raw_attribute = subject.class.send(name.to_s.pluralize)[attribute]
!(Array(value).map(&:to_s) & [attribute, raw_attribute]).empty?
end
private
def build_joins_relation(relation, *where_conditions)
strategy_class.new(adapter: self, relation: relation, where_conditions: where_conditions).execute!
end
def strategy_class
strategy_class_name = CanCan.accessible_by_strategy.to_s.camelize
CanCan::ModelAdapters::Strategies.const_get(strategy_class_name)
end
def sanitize_sql(conditions)
if conditions.is_a?(Hash)
sanitize_sql_activerecord5(conditions)
else
@model_class.send(:sanitize_sql, conditions)
end
end
def sanitize_sql_activerecord5(conditions)
table = @model_class.send(:arel_table)
table_metadata = ActiveRecord::TableMetadata.new(@model_class, table)
predicate_builder = ActiveRecord::PredicateBuilder.new(table_metadata)
predicate_builder.build_from_hash(conditions.stringify_keys).map { |b| visit_nodes(b) }.join(' AND ')
end
def visit_nodes(node)
# Rails 5.2 adds a BindParam node that prevents the visitor method from properly compiling the SQL query
if self.class.version_greater_or_equal?('5.2.0')
connection = @model_class.send(:connection)
collector = Arel::Collectors::SubstituteBinds.new(connection, Arel::Collectors::SQLString.new)
connection.visitor.accept(node, collector).value
else
@model_class.send(:connection).visitor.compile(node)
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/abstract_adapter.rb | lib/cancan/model_adapters/abstract_adapter.rb | # frozen_string_literal: true
module CanCan
module ModelAdapters
class AbstractAdapter
attr_reader :model_class
def self.inherited(subclass)
@subclasses ||= []
@subclasses.insert(0, subclass)
end
def self.adapter_class(model_class)
@subclasses.detect { |subclass| subclass.for_class?(model_class) } || DefaultAdapter
end
# Used to determine if the given adapter should be used for the passed in class.
def self.for_class?(_member_class)
false # override in subclass
end
# Override if you need custom find behavior
def self.find(model_class, id)
model_class.find(id)
end
# Used to determine if this model adapter will override the matching behavior for a hash of conditions.
# If this returns true then matches_conditions_hash? will be called. See Rule#matches_conditions_hash
def self.override_conditions_hash_matching?(_subject, _conditions)
false
end
# Override if override_conditions_hash_matching? returns true
def self.matches_conditions_hash?(_subject, _conditions)
raise NotImplemented, 'This model adapter does not support matching on a conditions hash.'
end
# Override if parent condition could be under a different key in conditions
def self.parent_condition_name(parent, _child)
parent.class.name.downcase.to_sym
end
# Used above override_conditions_hash_matching to determine if this model adapter will override the
# matching behavior for nested subject.
# If this returns true then nested_subject_matches_conditions? will be called.
def self.override_nested_subject_conditions_matching?(_parent, _child, _all_conditions)
false
end
# Override if override_nested_subject_conditions_matching? returns true
def self.nested_subject_matches_conditions?(_parent, _child, _all_conditions)
raise NotImplemented, 'This model adapter does not support matching on a nested subject.'
end
# Used to determine if this model adapter will override the matching behavior for a specific condition.
# If this returns true then matches_condition? will be called. See Rule#matches_conditions_hash
def self.override_condition_matching?(_subject, _name, _value)
false
end
# Override if override_condition_matching? returns true
def self.matches_condition?(_subject, _name, _value)
raise NotImplemented, 'This model adapter does not support matching on a specific condition.'
end
def initialize(model_class, rules)
@model_class = model_class
@rules = rules
end
def database_records
# This should be overridden in a subclass to return records which match @rules
raise NotImplemented, 'This model adapter does not support fetching records from the database.'
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/strategies/joined_alias_each_rule_as_exists_subquery.rb | lib/cancan/model_adapters/strategies/joined_alias_each_rule_as_exists_subquery.rb | # frozen_string_literal: false
module CanCan
module ModelAdapters
class Strategies
class JoinedAliasEachRuleAsExistsSubquery < Base
def execute!
model_class
.joins(
"JOIN #{quoted_table_name} AS #{quoted_aliased_table_name} ON " \
"#{quoted_aliased_table_name}.#{quoted_primary_key} = #{quoted_table_name}.#{quoted_primary_key}"
)
.where(double_exists_sql)
end
def double_exists_sql
double_exists_sql = ''
compressed_rules.each_with_index do |rule, index|
double_exists_sql << ' OR ' if index.positive?
double_exists_sql << "EXISTS (#{sub_query_for_rule(rule).to_sql})"
end
double_exists_sql
end
def sub_query_for_rule(rule)
conditions_extractor = ConditionsExtractor.new(model_class)
rule_where_conditions = extract_multiple_conditions(conditions_extractor, [rule])
joins_hash, left_joins_hash = extract_joins_from_rule(rule)
sub_query_for_rules_and_join_hashes(rule_where_conditions, joins_hash, left_joins_hash)
end
def sub_query_for_rules_and_join_hashes(rule_where_conditions, joins_hash, left_joins_hash)
model_class
.select('1')
.joins(joins_hash)
.left_joins(left_joins_hash)
.where(
"#{quoted_table_name}.#{quoted_primary_key} = " \
"#{quoted_aliased_table_name}.#{quoted_primary_key}"
)
.where(rule_where_conditions)
.limit(1)
end
def extract_joins_from_rule(rule)
joins = {}
left_joins = {}
extra_joins_recursive([], rule.conditions, joins, left_joins)
[joins, left_joins]
end
def extra_joins_recursive(current_path, conditions, joins, left_joins)
conditions.each do |key, value|
if value.is_a?(Hash)
current_path << key
extra_joins_recursive(current_path, value, joins, left_joins)
current_path.pop
else
extra_joins_recursive_merge_joins(current_path, value, joins, left_joins)
end
end
end
def extra_joins_recursive_merge_joins(current_path, value, joins, left_joins)
hash_joins = current_path_to_hash(current_path)
if value.nil?
left_joins.deep_merge!(hash_joins)
else
joins.deep_merge!(hash_joins)
end
end
# Converts an array like [:child, :grand_child] into a hash like {child: {grand_child: {}}
def current_path_to_hash(current_path)
hash_joins = {}
current_hash_joins = hash_joins
current_path.each do |path_part|
new_hash = {}
current_hash_joins[path_part] = new_hash
current_hash_joins = new_hash
end
hash_joins
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/strategies/left_join.rb | lib/cancan/model_adapters/strategies/left_join.rb | module CanCan
module ModelAdapters
class Strategies
class LeftJoin < Base
def execute!
relation.left_joins(joins).distinct
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/strategies/base.rb | lib/cancan/model_adapters/strategies/base.rb | module CanCan
module ModelAdapters
class Strategies
class Base
attr_reader :adapter, :relation, :where_conditions
delegate(
:compressed_rules,
:extract_multiple_conditions,
:joins,
:model_class,
:quoted_primary_key,
:quoted_aliased_table_name,
:quoted_table_name,
to: :adapter
)
delegate :connection, :quoted_primary_key, to: :model_class
delegate :quote_table_name, to: :connection
def initialize(adapter:, relation:, where_conditions:)
@adapter = adapter
@relation = relation
@where_conditions = where_conditions
end
def aliased_table_name
@aliased_table_name ||= "#{model_class.table_name}_alias"
end
def quoted_aliased_table_name
@quoted_aliased_table_name ||= quote_table_name(aliased_table_name)
end
def quoted_table_name
@quoted_table_name ||= quote_table_name(model_class.table_name)
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/strategies/subquery.rb | lib/cancan/model_adapters/strategies/subquery.rb | module CanCan
module ModelAdapters
class Strategies
class Subquery < Base
def execute!
build_joins_relation_subquery(where_conditions)
end
def build_joins_relation_subquery(where_conditions)
inner = model_class.unscoped do
model_class.left_joins(joins).where(*where_conditions)
end
model_class.where(model_class.primary_key => inner)
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/cancan/model_adapters/strategies/joined_alias_exists_subquery.rb | lib/cancan/model_adapters/strategies/joined_alias_exists_subquery.rb | # frozen_string_literal: true
module CanCan
module ModelAdapters
class Strategies
class JoinedAliasExistsSubquery < Base
def execute!
model_class
.joins(
"JOIN #{quoted_table_name} AS #{quoted_aliased_table_name} ON " \
"#{quoted_aliased_table_name}.#{quoted_primary_key} = #{quoted_table_name}.#{quoted_primary_key}"
)
.where("EXISTS (#{joined_alias_exists_subquery_inner_query.to_sql})")
end
def joined_alias_exists_subquery_inner_query
model_class
.unscoped
.select('1')
.left_joins(joins)
.where(*where_conditions)
.where(
"#{quoted_table_name}.#{quoted_primary_key} = " \
"#{quoted_aliased_table_name}.#{quoted_primary_key}"
)
.limit(1)
end
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/generators/cancan/ability/ability_generator.rb | lib/generators/cancan/ability/ability_generator.rb | # frozen_string_literal: true
module Cancan
module Generators
class AbilityGenerator < Rails::Generators::Base
source_root File.expand_path('templates', __dir__)
def generate_ability
copy_file 'ability.rb', 'app/models/ability.rb'
end
end
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
CanCanCommunity/cancancan | https://github.com/CanCanCommunity/cancancan/blob/1100093bd2d3416bb875e1cb407a81ec35a6dab5/lib/generators/cancan/ability/templates/ability.rb | lib/generators/cancan/ability/templates/ability.rb | # frozen_string_literal: true
class Ability
include CanCan::Ability
def initialize(user)
# Define abilities for the user here. For example:
#
# return unless user.present?
# can :read, :all
# return unless user.admin?
# can :manage, :all
#
# The first argument to `can` is the action you are giving the user
# permission to do.
# If you pass :manage it will apply to every action. Other common actions
# here are :read, :create, :update and :destroy.
#
# The second argument is the resource the user can perform the action on.
# If you pass :all it will apply to every resource. Otherwise pass a Ruby
# class of the resource.
#
# The third argument is an optional hash of conditions to further filter the
# objects.
# For example, here the user can only update published articles.
#
# can :update, Article, published: true
#
# See the wiki for details:
# https://github.com/CanCanCommunity/cancancan/blob/develop/docs/define_check_abilities.md
end
end
| ruby | MIT | 1100093bd2d3416bb875e1cb407a81ec35a6dab5 | 2026-01-04T15:42:48.048224Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/init.rb | init.rb | require 'will_paginate'
# This is all duplication of what Railtie does, but is necessary because
# the initializer defined by the Railtie won't ever run when loaded as plugin.
if defined? ActiveRecord::Base
require 'will_paginate/active_record'
end
if defined? ActionController::Base
WillPaginate::Railtie.setup_actioncontroller
end
if defined? ActionView::Base
require 'will_paginate/view_helpers/action_view'
end
WillPaginate::Railtie.add_locale_path config
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/console_fixtures.rb | spec/console_fixtures.rb | require 'bundler'
Bundler.setup
require 'will_paginate/active_record'
require 'finders/activerecord_test_connector'
ActiverecordTestConnector.setup
windows = RUBY_PLATFORM =~ /(:?mswin|mingw)/
# used just for the `color` method
log_subscriber = ActiveSupport::LogSubscriber.log_subscribers.first
IGNORE_SQL = /\b(sqlite_master|sqlite_version)\b|^(CREATE TABLE|PRAGMA)\b/
ActiveSupport::Notifications.subscribe(/^sql\./) do |*args|
data = args.last
unless data[:name] =~ /^Fixture/ or data[:sql] =~ IGNORE_SQL
if windows
puts data[:sql]
else
puts log_subscriber.send(:color, data[:sql], :cyan)
end
end
end
# load all fixtures
ActiverecordTestConnector::Fixtures.create_fixtures \
ActiverecordTestConnector::FIXTURES_PATH, ActiveRecord::Base.connection.tables
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/page_number_spec.rb | spec/page_number_spec.rb | require 'spec_helper'
require 'will_paginate/page_number'
require 'json'
RSpec.describe WillPaginate::PageNumber do
describe "valid" do
def num
WillPaginate::PageNumber.new('12', 'page')
end
it "== 12" do
expect(num).to eq(12)
end
it "inspects to 'page 12'" do
expect(num.inspect).to eq('page 12')
end
it "is a PageNumber" do
expect(num.instance_of? WillPaginate::PageNumber).to be
end
it "is a kind of Numeric" do
expect(num.is_a? Numeric).to be
end
it "is a kind of Integer" do
expect(num.is_a? Integer).to be
end
it "isn't directly a Integer" do
expect(num.instance_of? Integer).not_to be
end
it "passes the PageNumber=== type check" do |variable|
expect(WillPaginate::PageNumber === num).to be
end
it "passes the Numeric=== type check" do |variable|
expect(Numeric === num).to be
end
it "fails the Numeric=== type check" do |variable|
expect(Integer === num).not_to be
end
it "serializes as JSON number" do
expect(JSON.dump(page: num)).to eq('{"page":12}')
end
end
describe "invalid" do
def create(value, name = 'page')
described_class.new(value, name)
end
it "errors out on non-int values" do
expect { create(nil) }.to raise_error(WillPaginate::InvalidPage)
expect { create('') }.to raise_error(WillPaginate::InvalidPage)
expect { create('Schnitzel') }.to raise_error(WillPaginate::InvalidPage)
end
it "errors out on zero or less" do
expect { create(0) }.to raise_error(WillPaginate::InvalidPage)
expect { create(-1) }.to raise_error(WillPaginate::InvalidPage)
end
it "doesn't error out on zero for 'offset'" do
expect { create(0, 'offset') }.not_to raise_error
expect { create(-1, 'offset') }.to raise_error(WillPaginate::InvalidPage)
end
end
describe "coercion method" do
it "defaults to 'page' name" do
num = WillPaginate::PageNumber(12)
expect(num.inspect).to eq('page 12')
end
it "accepts a custom name" do
num = WillPaginate::PageNumber(12, 'monkeys')
expect(num.inspect).to eq('monkeys 12')
end
it "doesn't affect PageNumber instances" do
num = WillPaginate::PageNumber(12)
num2 = WillPaginate::PageNumber(num)
expect(num2.object_id).to eq(num.object_id)
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/per_page_spec.rb | spec/per_page_spec.rb | require 'spec_helper'
require 'will_paginate/per_page'
RSpec.describe WillPaginate::PerPage do
class MyModel
extend WillPaginate::PerPage
end
it "has the default value" do
expect(MyModel.per_page).to eq(30)
WillPaginate.per_page = 10
begin
expect(MyModel.per_page).to eq(10)
ensure
WillPaginate.per_page = 30
end
end
it "casts values to int" do
WillPaginate.per_page = '10'
begin
expect(MyModel.per_page).to eq(10)
ensure
WillPaginate.per_page = 30
end
end
it "has an explicit value" do
MyModel.per_page = 12
begin
expect(MyModel.per_page).to eq(12)
subclass = Class.new(MyModel)
expect(subclass.per_page).to eq(12)
ensure
MyModel.send(:remove_instance_variable, '@per_page')
end
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
mislav/will_paginate | https://github.com/mislav/will_paginate/blob/50017c3eb0712e7b3a53268a81e81a184b7a49f6/spec/collection_spec.rb | spec/collection_spec.rb | require 'will_paginate/array'
require 'spec_helper'
RSpec.describe WillPaginate::Collection do
before :all do
@simple = ('a'..'e').to_a
end
it "should be a subset of original collection" do
expect(@simple.paginate(:page => 1, :per_page => 3)).to eq(%w( a b c ))
end
it "can be shorter than per_page if on last page" do
expect(@simple.paginate(:page => 2, :per_page => 3)).to eq(%w( d e ))
end
it "should include whole collection if per_page permits" do
expect(@simple.paginate(:page => 1, :per_page => 5)).to eq(@simple)
end
it "should be empty if out of bounds" do
expect(@simple.paginate(:page => 2, :per_page => 5)).to be_empty
end
it "should default to 1 as current page and 30 per-page" do
result = (1..50).to_a.paginate
expect(result.current_page).to eq(1)
expect(result.size).to eq(30)
end
it "should give total_entries precedence over actual size" do
expect(%w(a b c).paginate(:total_entries => 5).total_entries).to eq(5)
end
it "should be an augmented Array" do
entries = %w(a b c)
collection = create(2, 3, 10) do |pager|
expect(pager.replace(entries)).to eq(entries)
end
expect(collection).to eq(entries)
for method in %w(total_pages each offset size current_page per_page total_entries)
expect(collection).to respond_to(method)
end
expect(collection).to be_kind_of(Array)
expect(collection.entries).to be_instance_of(Array)
# TODO: move to another expectation:
expect(collection.offset).to eq(3)
expect(collection.total_pages).to eq(4)
expect(collection).not_to be_out_of_bounds
end
describe "previous/next pages" do
it "should have previous_page nil when on first page" do
collection = create(1, 1, 3)
expect(collection.previous_page).to be_nil
expect(collection.next_page).to eq(2)
end
it "should have both prev/next pages" do
collection = create(2, 1, 3)
expect(collection.previous_page).to eq(1)
expect(collection.next_page).to eq(3)
end
it "should have next_page nil when on last page" do
collection = create(3, 1, 3)
expect(collection.previous_page).to eq(2)
expect(collection.next_page).to be_nil
end
end
describe "out of bounds" do
it "is out of bounds when page number is too high" do
expect(create(2, 3, 2)).to be_out_of_bounds
end
it "isn't out of bounds when inside collection" do
expect(create(1, 3, 2)).not_to be_out_of_bounds
end
it "isn't out of bounds when the collection is empty" do
collection = create(1, 3, 0)
expect(collection).not_to be_out_of_bounds
expect(collection.total_pages).to eq(1)
end
end
describe "guessing total count" do
it "can guess when collection is shorter than limit" do
collection = create { |p| p.replace array }
expect(collection.total_entries).to eq(8)
end
it "should allow explicit total count to override guessed" do
collection = create(2, 5, 10) { |p| p.replace array }
expect(collection.total_entries).to eq(10)
end
it "should not be able to guess when collection is same as limit" do
collection = create { |p| p.replace array(5) }
expect(collection.total_entries).to be_nil
end
it "should not be able to guess when collection is empty" do
collection = create { |p| p.replace array(0) }
expect(collection.total_entries).to be_nil
end
it "should be able to guess when collection is empty and this is the first page" do
collection = create(1) { |p| p.replace array(0) }
expect(collection.total_entries).to eq(0)
end
end
it "should not respond to page_count anymore" do
expect { create.page_count }.to raise_error(NoMethodError)
end
it "inherits per_page from global value" do
collection = described_class.new(1)
expect(collection.per_page).to eq(30)
end
private
def create(page = 2, limit = 5, total = nil, &block)
if block_given?
described_class.create(page, limit, total, &block)
else
described_class.new(page, limit, total)
end
end
def array(size = 3)
Array.new(size)
end
end
| ruby | MIT | 50017c3eb0712e7b3a53268a81e81a184b7a49f6 | 2026-01-04T15:42:46.511340Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.