text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_prefix|>use {
regex_automata::meta::Regex,
regex_syntax::hir::{
self, Hir,
literal::{Literal, Seq},
},
};
use crate::{config::ConfiguredHIR, error::Error};
/// A type that encapsulates "inner" literal extractiong from a regex.
///
/// It uses a huge pile of heuristics to try to pluck... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use {
grep_matcher::{
ByteSet, Captures, LineMatchKind, LineTerminator, Match, Matcher,
NoError,
},
regex_automata::{
Input, PatternID, meta::Regex,
util::captures::Captures as AutomataCaptures,
},
};
use crate::{config::Config, error::Error, literal::Inner... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>b in lit.iter() {
set.remove(b);
}
}
HirKind::Class(hir::Class::Unicode(ref cls)) => {
for range in cls.iter() {
// This is presumably faster than encoding every codepoint
// to UTF-8 and then removing those bytes from... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>())
}
}
/// The implementation of strip_from_match. The given byte must be ASCII.
/// This function returns an error otherwise. It also returns an error if
/// it couldn't remove `\n` from the given regex without leaving an empty
/// character class in its place.
fn strip_from_match_ascii(expr: Hir, ... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> Ok(true)
}),
)?;
Ok(())
}
<|fim_prefix|>use std::env;
use<|fim_middle|> std::error::Error;
use std::io;
use std::process;
use grep_regex::RegexMatcher;
use grep_searcher::Searcher;
use grep_searcher::sinks::UTF8;
fn main() {
if let Err(err) = example() {
eprintln!("{}", err)... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>Context, SinkContextKind, SinkError, SinkFinish, SinkMatch,
sinks,
},
};
#[macro_use]
mod macros;
mod line_buffer;
mod lines;
mod searcher;
mod sink;
#[cfg(test)]
mod testutil;
<|fim_prefix|>/*!
This crate provides an implementation of line oriented search, with optional
support for multi-li... | fim | BurntSushi/ripgrep | rust |
use std::io;
use bstr::ByteSlice;
/// The default buffer capacity that we use for the line buffer.
pub(crate) const DEFAULT_BUFFER_CAPACITY: usize = 64 * (1 << 10); // 64 KB
/// The behavior of a searcher in the face of long lines and big contexts.
///
/// When searching data incrementally using a fixed size buffer,... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> vec!["abc\n", "\n"]);
assert_eq!(lines("abc\n\n\n"), vec!["abc\n", "\n", "\n"]);
assert_eq!(lines("abc\n\nxyz"), vec!["abc\n", "\n", "xyz"]);
assert_eq!(lines("abc\n\nxyz\n"), vec!["abc\n", "\n", "xyz\n"]);
assert_eq!(lines("abc\nxyz\n\n"), vec!["abc\n", "xyz\n", "\n"]);
... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>got:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
{}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
", label, expected, got);
}
}
}
<|fim_prefix|>/// Like assert_eq, but nicer output for long strings.
#[cfg(test)]
#[macro_expo... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> buf: &[u8],
upto: usize,
) -> Result<bool, S::Error> {
let range = Range::new(self.last_line_visited, upto);
let mut stepper = LineStep::new(
self.config.line_term.as_byte(),
range.start(),
range.end(),
);
while let Some(line... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use grep_matcher::Matcher;
use crate::{
line_buffer::{DEFAULT_BUFFER_CAPACITY, LineBufferReader},
lines::{self, LineStep},
searcher::{Config, Range, Searcher, core::Core},
sink::{Sink, SinkError},
};
#[derive(Debug)]
pub(crate) struct ReadByLine<'s, M, R, S> {
config: &'s Config,
... | fim | BurntSushi/ripgrep | rust |
use std::{fs::File, path::Path};
use memmap::Mmap;
/// Controls the strategy used for determining when to use memory maps.
///
/// If a searcher is called in circumstances where it is possible to use memory
/// maps, and memory maps are enabled, then it will attempt to do so if it
/// believes it will make the search... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> M: Matcher,
S: Sink,
{
if let Some(mmap) = self.config.mmap.open(file, path) {
log::trace!("{:?}: searching via memory map", path);
return self.search_slice(matcher, &mmap, write_to);
}
// Fast path for multi-line searches of files when mem... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::io;
use grep_matcher::LineTerminator;
use crate::{
lines::LineIter,
searcher::{ConfigError, Searcher},
};
/// A trait that describes errors that can be reported by searchers and
/// implementations of `Sink`.
///
/// Unless you have a specialized use case, you probably don't need to
//... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use std::io::{self, Write};
use {
bstr::ByteSlice,
grep_matcher::{
LineMatchKind, LineTerminator, Match, Matcher, NoCaptures, NoError,
},
regex::bytes::{Regex, RegexBuilder},
};
use crate::{
searcher::{BinaryDetection, Searcher, SearcherBuilder},
sink::{Sink, SinkContext,... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>:glob` produces the same string as the original.
assert_eq!(glob.glob(), glob_str);
});
<|fim_prefix|>#![no_main]
use std::str::FromStr;
use globset::Glob;
libfuzzer_sys::fuzz_target!(|glob_str: &str| {
let Ok(glob) = Glob::new(glob_str) else {
r<|fim_middle|>eturn;
};
let Ok(g... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>class RipgrepBin < Formula
version '15.0.0'
desc "Recursively search directories for a r<|fim_suffix|>pgrep-#{version}-x86_64-unknown-linux-musl.tar.gz"
sha256 "1c9297be4a084eea7ecaedf93eb03d058d6faae29bbc57ecdaf5063921491599"
end
conflicts_with "ripgrep"
def install
bin.install "rg"... | fim | BurntSushi/ripgrep | ruby |
<|fim_suffix|>d.
rgtest!(before_match1_implicit_text, |dir: Dir, mut cmd: TestCommand| {
dir.create_bytes("hay", HAY);
cmd.args(&["--no-mmap", "-n", "--text", "Heaven", "-g", "hay"]);
let expected = "\
hay:1871:\"No. Heaven knows what the objects of his studies are. But here we
";
eqnice!(expected, cmd... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use crate::hay::{SHERLOCK, SHERLOCK_CRLF};
use crate::util::{Dir, TestCommand, sort_lines};
// See: https://github.com/BurntSushi/ripgrep/issues/1
rgtest!(f1_sjis, |dir: Dir, mut cmd: TestCommand| {
dir.create_bytes(
"foo",
b"\x84Y\x84u\x84\x82\x84|\x84\x80\x84{ \x84V\x84\x80\x84|\x84... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>pub const SHERLOCK: &'static str = "\
For the Doctor Watsons of this world, as opposed to the Sherlock
Holmeses, success in the province of detective work must always
be, to a very large extent, the result of luck. Sherlock Holmes
can extract a clew from a wisp of straw or a <|fim_suffix|>aken out for him... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>f luck. \
Sherlock Holmes\n",
),
line_number: Some(3),
absolute_offset: 129,
submatches: vec![SubMatch {
m: Data::text("Sherlock Holmes"),
replacement: Some(Data::text("John Watson")),
start: 4... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>#[macro_export]
macro_rules! rgtest {
($name:ident, $fun:expr) => {
#[test]
fn $name() {
let (dir, cmd) = crate::util::setup(stringify!($name));
$fun(dir, cmd);
if cfg!(feature = "pcre2") {
let (dir, cmd) = crate::util::setup_pcre2(s... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use crate::hay::SHERLOCK;
use crate::util::{Dir, TestCommand, cmd_exists, sort_lines};
// This file contains "miscellaneous" tests that were either written before
// features were tracked more explicitly, or were simply written without
// linking them to a specific issue number. We should try to minimize... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>);
});
// Tests that even in a multiline search, a '.' does not match a newline.
rgtest!(dot_no_newline, |dir: Dir, mut cmd: TestCommand| {
dir.create("sherlock", SHERLOCK);
cmd.args(&["-n", "-U", "of this world.+detective work", "sherlock"]);
cmd.assert_err();
});
// Tests that the --multil... | fim | BurntSushi/ripgrep | rust |
<|fim_prefix|>use crate::hay::SHERLOCK;
use crate::util::{Dir, TestCommand, sort_lines};
// See: https://github.com/BurntSushi/ripgrep/issues/16
rgtest!(r16, |dir: Dir, mut cmd: TestCommand| {
dir.create_dir(".git");
dir.create(".gitignore", "ghi/");
dir.create_dir("ghi");
dir.create_dir("def/ghi");
... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|>nary;
// Tests related to most features in ripgrep. If you're adding something new
// to ripgrep, tests should probably go in here.
mod feature;
// Tests for ripgrep's JSON format.
mod json;
// Miscellaneous tests grouped in a haphazard manner. Try not to add more.
mod misc;
// Tests for ripgrep's multili... | fim | BurntSushi/ripgrep | rust |
use std::env;
use std::error;
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::{self, Command};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
use std::time::Duration;
use bstr::ByteSlice;
static TEST_DIR: &'static str = "r... | fim | BurntSushi/ripgrep | rust |
<|fim_suffix|> "ş": "s",
"ü": "u",
"Ç": "C",
"Ə": "E",
"Ğ": "G",
"İ": "I",
"Ö": "O",
"Ş": "S",
"Ü": "U"
},
"cs": {
// Czech
"č": "c",
"ď": "d",
"ě": "e",
"ň": "n",
... | fim | CanCanCommunity/cancancan | javascript |
import {
DefaultMagicKeysAliasMap,
StorageSerializers,
TransitionPresets,
assert,
breakpointsAntDesign,
breakpointsBootstrapV5,
breakpointsMasterCss,
breakpointsPrimeFlex,
breakpointsQuasar,
breakpointsSematic,
breakpointsTailwind,
breakpointsVuetify,
breakpointsVuetifyV2,
breakpointsVuetify... | fim | CanCanCommunity/cancancan | javascript |
<|fim_prefix|>import {
tryOnScopeDispose,
unrefElement
} from "./chunk-ZEI2HCB7.js";
import {
ref,
watch
} from "./chunk-RY5ODQAQ.js";
// node_modules/tabbable/dist/index.esm.js
var candidateSelectors = ["input:not([inert])", "select:not([inert])", "textarea:not([inert])", "a[href]:not([inert])", "button:not([... | fim | CanCanCommunity/cancancan | javascript |
<|fim_suffix|>);
}
repl.textContent = startNode.textContent;
startNode.parentNode.replaceChild(repl, startNode);
return ret;
}
/**
* @typedef Mark~wrapRangeInMappedTextNodeDict
* @type {object.<string>}
* @property {string} value - The composite value of all text nodes
* @property {objec... | fim | CanCanCommunity/cancancan | javascript |
<|fim_suffix|>);
var fieldId = this._fieldIds[field];
var uniqueTerms = new Set(tokens).size;
this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
try {
for (var tokens_1 = (e_2 = void 0, __values(tokens)), tokens_1_1 = tokens_1.next();... | fim | CanCanCommunity/cancancan | javascript |
<|fim_suffix|> toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useModel,
useSSRContext,
useSlots,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
wa... | fim | CanCanCommunity/cancancan | javascript |
<|fim_prefix|>// https://vitepress.dev/guide/custom-theme
import { h } from 'vue'
import type { Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import './style.css'
export default {
extends: DefaultTheme,
<|fim_suffix|>.dev/guide/extending-default-theme#layout-slots
})
},
enhanceApp({ app... | fim | CanCanCommunity/cancancan | typescript |
<|fim_prefix|># frozen_string_literal: true
r<|fim_suffix|><|fim_middle|>equire 'cancan'
<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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<|fim_suffix|>ns(aliases)
end
end
expanded
end
en... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>e, 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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> 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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_literal: true
require_relative 'ability/rules.rb'
require_relative 'ability/actions.rb<|fim_suffix|>ct|
relevant_rules_for_match(action, a_subject).detect do |rule|
rule.matches_conditions?(action, a_subject, attribute, *extra_args) && rule.matches_attributes?(attribute)... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>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|
... | fim | CanCanCommunity/cancancan | ruby |
# 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, attribu... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> 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
<|fim_prefix|># frozen_string_literal: true
module CanCan... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> #
# [:+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 lo... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>].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 ... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_literal: true
modu<|fim_suffix|> 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
<|fim_middle|>le CanCan
module ... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>hod_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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> 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
# ... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>
[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
<|fim_prefix|># frozen_string_literal: true
module CanCan
module Controlle... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>nstance_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?
... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>"
end
end
end
<|fim_prefix|># 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 ... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>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
<|fim_prefix|># frozen_string_literal: true... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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.detec... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>olve_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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ditions. ' \
"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_em... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ble_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
<|fim_prefix|># frozen_string_literal: true
# this class is responsible of converting the hash of conditio... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> end
end
end
end
<|fim_prefix|># 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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ing_literal: true
module CanCan
module ModelAdapters
class DefaultAdapter < AbstractAdapter
# This adapter is used when no matching adapter is found
end
end
end
<|fim_prefix|># frozen_st<|fim_middle|>r<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>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)
r... | fim | CanCanCommunity/cancancan | ruby |
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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>oins)
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: {gran... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_literal: true
module CanCan
module ModelAdapters
class Strategies
class JoinedAliasExistsSubquer<|fim_suffix|>able_name}.#{quoted_primary_key}"
)
.where("EXISTS (#{joined_alias_exists_subquery_inner_query.to_sql})")
end
def joined_alias... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> class Strategies
class LeftJoin < Base
def execute!
relation.left_joins(joins).distinct
end
end
end
end
end
<|fim_prefix|>module CanCan
m<|fim_middle|>odule ModelAdapters
<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>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.le... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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 acti... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>bute.is_a?(Symbol) || (attribute.is_a?(Array) && attribute.all? { |a| a.is_a?(Symbol) })
end
end
end
<|fim_prefix|># frozen_string_literal: true
module CanCan
module ParameterValidators
def valid_attribute_param?(attribute)
attr<|fim_middle|>ibute.nil? || attri<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>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?(:mana... | fim | CanCanCommunity/cancancan | ruby |
# 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 ... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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)
ar... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_<|fim_suffix|>ctive_record?)
return false if subject == :all || subject.descends_from_active_record?
return false unless subject < ActiveRecord::Base
true
end
end
<|fim_middle|>literal: true
class StiDetector
def self.sti_class?(subject)
return false unless defined?(A... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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(ac<|fim_suffix|>nslate("actions.#{action}", default: action.to_s)
variable... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_literal: t<|fim_suffix|>
module CanCan
VERSION = '3.6.0'.freeze
end
<|fim_middle|>rue<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>adapters/strategies/joined_alias_exists_subquery'
require 'cancan/model_adapters/strategies/left_join'
require 'cancan/model_adapters/strategies/subquery'
end
<|fim_prefix|>#<|fim_middle|> frozen_string_literal: true
require 'cancan/version'
require 'cancan/config'
require 'cancan/parameter_validator... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ncan'
module CanCanCan
end
<|fim_prefix|># frozen_string_literal: true
<|fim_middle|>require 'ca<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_literal: true
module Cancan
module Generators
class AbilityGenerator < Rails::Generators::Base
source_root File.expand_path('templates'<|fim_suffix|>_file 'ability.rb', 'app/models/ability.rb'
end
end
end
end
<|fim_middle|>, __dir__)
def generate_ability
... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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 :firs... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>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(:... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ze_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 }
resou... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>e_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 = 'Unauth... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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 f... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ikes: :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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>cessible).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(@ab... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|> 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
<|fim_prefix|># frozen_string_literal: true
requ... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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}"... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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 :visi... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>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
... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># frozen_string_literal: true
requ<|fim_suffix|>nCan::ModelAdapters::DefaultAdapter)
end
end
<|fim_middle|>ire 'spec_helper'
describe CanCan::ModelAdapters::DefaultAdapter do
it 'is default for generic classes' do
expect(CanCan::ModelAdapters::AbstractAdapter.adapter_class(Object)).to eq(Ca<|end... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>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
ActiveRe... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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, act... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>tly 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
<|fim_prefix|># frozen_string_literal: true
require 'spec_helper'
require 'ostruct' # for OpenStr... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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(... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>lized_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
<|fim_prefix|># frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
Bundler.require
requi... | fim | CanCanCommunity/cancancan | ruby |
<|fim_suffix|>ialize(user)
end
end
<|fim_prefix|># frozen_string_literal: true
class Ability
include CanCan::Ability
<|fim_middle|>
def init<|endoftext|> | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|># 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(STDOU... | fim | CanCanCommunity/cancancan | ruby |
<|fim_prefix|>#r "nuget: Fli"
open Fli
// Empty output directory
cli {
Shell PWSH
Command "Remove-Item * -Include *.nupkg"
WorkingDirectory "src/.nupkg/"
}
|> Command.execute
|> Output.toText
|> printfn "%s"
// Build in Release configuration
cli {
Exec "dotnet"
Argu<|fim_suffix|>Output.toText
|> ... | fim | CaptnCodr/Fli | fsharp |
<|fim_prefix|>module AssemblyInfo
open System.Runtime.CompilerServices
[<assembl<|fim_suffix|>ibleTo("Fli.Tests")>]
do ()
<|fim_middle|>y: InternalsVis<|endoftext|> | fim | CaptnCodr/Fli | fsharp |
namespace Fli
[<AutoOpen>]
module CE =
open System.Text
open System.IO
open Domain
type ICommandContext<'a> with
member this.Yield _ = this
type StartingContext =
{ config: Config option }
member this.CurrentConfig = this.config |> Option.defaultValue Defaults
... | fim | CaptnCodr/Fli | fsharp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.