id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,600
|
ruby-i18n/i18n
|
lib/i18n/config.rb
|
I18n.Config.missing_interpolation_argument_handler
|
def missing_interpolation_argument_handler
@@missing_interpolation_argument_handler ||= lambda do |missing_key, provided_hash, string|
raise MissingInterpolationArgument.new(missing_key, provided_hash, string)
end
end
|
ruby
|
def missing_interpolation_argument_handler
@@missing_interpolation_argument_handler ||= lambda do |missing_key, provided_hash, string|
raise MissingInterpolationArgument.new(missing_key, provided_hash, string)
end
end
|
[
"def",
"missing_interpolation_argument_handler",
"@@missing_interpolation_argument_handler",
"||=",
"lambda",
"do",
"|",
"missing_key",
",",
"provided_hash",
",",
"string",
"|",
"raise",
"MissingInterpolationArgument",
".",
"new",
"(",
"missing_key",
",",
"provided_hash",
",",
"string",
")",
"end",
"end"
] |
Returns the current handler for situations when interpolation argument
is missing. MissingInterpolationArgument will be raised by default.
|
[
"Returns",
"the",
"current",
"handler",
"for",
"situations",
"when",
"interpolation",
"argument",
"is",
"missing",
".",
"MissingInterpolationArgument",
"will",
"be",
"raised",
"by",
"default",
"."
] |
0c5dab494d9b043e00662d8e789229c33045c024
|
https://github.com/ruby-i18n/i18n/blob/0c5dab494d9b043e00662d8e789229c33045c024/lib/i18n/config.rb#L97-L101
|
12,601
|
ruby-i18n/i18n
|
lib/i18n.rb
|
I18n.Base.translate
|
def translate(key = nil, *, throw: false, raise: false, locale: nil, **options) # TODO deprecate :raise
locale ||= config.locale
raise Disabled.new('t') if locale == false
enforce_available_locales!(locale)
backend = config.backend
result = catch(:exception) do
if key.is_a?(Array)
key.map { |k| backend.translate(locale, k, options) }
else
backend.translate(locale, key, options)
end
end
if result.is_a?(MissingTranslation)
handle_exception((throw && :throw || raise && :raise), result, locale, key, options)
else
result
end
end
|
ruby
|
def translate(key = nil, *, throw: false, raise: false, locale: nil, **options) # TODO deprecate :raise
locale ||= config.locale
raise Disabled.new('t') if locale == false
enforce_available_locales!(locale)
backend = config.backend
result = catch(:exception) do
if key.is_a?(Array)
key.map { |k| backend.translate(locale, k, options) }
else
backend.translate(locale, key, options)
end
end
if result.is_a?(MissingTranslation)
handle_exception((throw && :throw || raise && :raise), result, locale, key, options)
else
result
end
end
|
[
"def",
"translate",
"(",
"key",
"=",
"nil",
",",
"*",
",",
"throw",
":",
"false",
",",
"raise",
":",
"false",
",",
"locale",
":",
"nil",
",",
"**",
"options",
")",
"# TODO deprecate :raise",
"locale",
"||=",
"config",
".",
"locale",
"raise",
"Disabled",
".",
"new",
"(",
"'t'",
")",
"if",
"locale",
"==",
"false",
"enforce_available_locales!",
"(",
"locale",
")",
"backend",
"=",
"config",
".",
"backend",
"result",
"=",
"catch",
"(",
":exception",
")",
"do",
"if",
"key",
".",
"is_a?",
"(",
"Array",
")",
"key",
".",
"map",
"{",
"|",
"k",
"|",
"backend",
".",
"translate",
"(",
"locale",
",",
"k",
",",
"options",
")",
"}",
"else",
"backend",
".",
"translate",
"(",
"locale",
",",
"key",
",",
"options",
")",
"end",
"end",
"if",
"result",
".",
"is_a?",
"(",
"MissingTranslation",
")",
"handle_exception",
"(",
"(",
"throw",
"&&",
":throw",
"||",
"raise",
"&&",
":raise",
")",
",",
"result",
",",
"locale",
",",
"key",
",",
"options",
")",
"else",
"result",
"end",
"end"
] |
Translates, pluralizes and interpolates a given key using a given locale,
scope, and default, as well as interpolation values.
*LOOKUP*
Translation data is organized as a nested hash using the upper-level keys
as namespaces. <em>E.g.</em>, ActionView ships with the translation:
<tt>:date => {:formats => {:short => "%b %d"}}</tt>.
Translations can be looked up at any level of this hash using the key argument
and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt>
returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>.
Key can be either a single key or a dot-separated key (both Strings and Symbols
work). <em>E.g.</em>, the short format can be looked up using both:
I18n.t 'date.formats.short'
I18n.t :'date.formats.short'
Scope can be either a single key, a dot-separated key or an array of keys
or dot-separated keys. Keys and scopes can be combined freely. So these
examples will all look up the same short date format:
I18n.t 'date.formats.short'
I18n.t 'formats.short', :scope => 'date'
I18n.t 'short', :scope => 'date.formats'
I18n.t 'short', :scope => %w(date formats)
*INTERPOLATION*
Translations can contain interpolation variables which will be replaced by
values passed to #translate as part of the options hash, with the keys matching
the interpolation variable names.
<em>E.g.</em>, with a translation <tt>:foo => "foo %{bar}"</tt> the option
value for the key +bar+ will be interpolated into the translation:
I18n.t :foo, :bar => 'baz' # => 'foo baz'
*PLURALIZATION*
Translation data can contain pluralized translations. Pluralized translations
are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>.
Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English
pluralization rules. Other algorithms can be supported by custom backends.
This returns the singular version of a pluralized translation:
I18n.t :foo, :count => 1 # => 'Foo'
These both return the plural version of a pluralized translation:
I18n.t :foo, :count => 0 # => 'Foos'
I18n.t :foo, :count => 2 # => 'Foos'
The <tt>:count</tt> option can be used both for pluralization and interpolation.
<em>E.g.</em>, with the translation
<tt>:foo => ['%{count} foo', '%{count} foos']</tt>, count will
be interpolated to the pluralized translation:
I18n.t :foo, :count => 1 # => '1 foo'
*DEFAULTS*
This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found:
I18n.t :foo, :default => 'default'
This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no
translation for <tt>:foo</tt> was found:
I18n.t :foo, :default => :bar
Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt>
or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found.
I18n.t :foo, :default => [:bar, 'default']
*BULK LOOKUP*
This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>.
I18n.t [:foo, :bar]
Can be used with dot-separated nested keys:
I18n.t [:'baz.foo', :'baz.bar']
Which is the same as using a scope option:
I18n.t [:foo, :bar], :scope => :baz
*LAMBDAS*
Both translations and defaults can be given as Ruby lambdas. Lambdas will be
called and passed the key and options.
E.g. assuming the key <tt>:salutation</tt> resolves to:
lambda { |key, options| options[:gender] == 'm' ? "Mr. #{options[:name]}" : "Mrs. #{options[:name]}" }
Then <tt>I18n.t(:salutation, :gender => 'w', :name => 'Smith') will result in "Mrs. Smith".
Note that the string returned by lambda will go through string interpolation too,
so the following lambda would give the same result:
lambda { |key, options| options[:gender] == 'm' ? "Mr. %{name}" : "Mrs. %{name}" }
It is recommended to use/implement lambdas in an "idempotent" way. E.g. when
a cache layer is put in front of I18n.translate it will generate a cache key
from the argument values passed to #translate. Therefor your lambdas should
always return the same translations/values per unique combination of argument
values.
|
[
"Translates",
"pluralizes",
"and",
"interpolates",
"a",
"given",
"key",
"using",
"a",
"given",
"locale",
"scope",
"and",
"default",
"as",
"well",
"as",
"interpolation",
"values",
"."
] |
0c5dab494d9b043e00662d8e789229c33045c024
|
https://github.com/ruby-i18n/i18n/blob/0c5dab494d9b043e00662d8e789229c33045c024/lib/i18n.rb#L179-L199
|
12,602
|
ruby-i18n/i18n
|
lib/i18n.rb
|
I18n.Base.exists?
|
def exists?(key, _locale = nil, locale: _locale)
locale ||= config.locale
raise Disabled.new('exists?') if locale == false
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
config.backend.exists?(locale, key)
end
|
ruby
|
def exists?(key, _locale = nil, locale: _locale)
locale ||= config.locale
raise Disabled.new('exists?') if locale == false
raise I18n::ArgumentError if key.is_a?(String) && key.empty?
config.backend.exists?(locale, key)
end
|
[
"def",
"exists?",
"(",
"key",
",",
"_locale",
"=",
"nil",
",",
"locale",
":",
"_locale",
")",
"locale",
"||=",
"config",
".",
"locale",
"raise",
"Disabled",
".",
"new",
"(",
"'exists?'",
")",
"if",
"locale",
"==",
"false",
"raise",
"I18n",
"::",
"ArgumentError",
"if",
"key",
".",
"is_a?",
"(",
"String",
")",
"&&",
"key",
".",
"empty?",
"config",
".",
"backend",
".",
"exists?",
"(",
"locale",
",",
"key",
")",
"end"
] |
Returns true if a translation exists for a given key, otherwise returns false.
|
[
"Returns",
"true",
"if",
"a",
"translation",
"exists",
"for",
"a",
"given",
"key",
"otherwise",
"returns",
"false",
"."
] |
0c5dab494d9b043e00662d8e789229c33045c024
|
https://github.com/ruby-i18n/i18n/blob/0c5dab494d9b043e00662d8e789229c33045c024/lib/i18n.rb#L210-L215
|
12,603
|
ruby-i18n/i18n
|
lib/i18n.rb
|
I18n.Base.localize
|
def localize(object, locale: nil, format: nil, **options)
locale ||= config.locale
raise Disabled.new('l') if locale == false
enforce_available_locales!(locale)
format ||= :default
config.backend.localize(locale, object, format, options)
end
|
ruby
|
def localize(object, locale: nil, format: nil, **options)
locale ||= config.locale
raise Disabled.new('l') if locale == false
enforce_available_locales!(locale)
format ||= :default
config.backend.localize(locale, object, format, options)
end
|
[
"def",
"localize",
"(",
"object",
",",
"locale",
":",
"nil",
",",
"format",
":",
"nil",
",",
"**",
"options",
")",
"locale",
"||=",
"config",
".",
"locale",
"raise",
"Disabled",
".",
"new",
"(",
"'l'",
")",
"if",
"locale",
"==",
"false",
"enforce_available_locales!",
"(",
"locale",
")",
"format",
"||=",
":default",
"config",
".",
"backend",
".",
"localize",
"(",
"locale",
",",
"object",
",",
"format",
",",
"options",
")",
"end"
] |
Localizes certain objects, such as dates and numbers to local formatting.
|
[
"Localizes",
"certain",
"objects",
"such",
"as",
"dates",
"and",
"numbers",
"to",
"local",
"formatting",
"."
] |
0c5dab494d9b043e00662d8e789229c33045c024
|
https://github.com/ruby-i18n/i18n/blob/0c5dab494d9b043e00662d8e789229c33045c024/lib/i18n.rb#L279-L286
|
12,604
|
ruby-i18n/i18n
|
lib/i18n.rb
|
I18n.Base.normalize_keys
|
def normalize_keys(locale, key, scope, separator = nil)
separator ||= I18n.default_separator
keys = []
keys.concat normalize_key(locale, separator)
keys.concat normalize_key(scope, separator)
keys.concat normalize_key(key, separator)
keys
end
|
ruby
|
def normalize_keys(locale, key, scope, separator = nil)
separator ||= I18n.default_separator
keys = []
keys.concat normalize_key(locale, separator)
keys.concat normalize_key(scope, separator)
keys.concat normalize_key(key, separator)
keys
end
|
[
"def",
"normalize_keys",
"(",
"locale",
",",
"key",
",",
"scope",
",",
"separator",
"=",
"nil",
")",
"separator",
"||=",
"I18n",
".",
"default_separator",
"keys",
"=",
"[",
"]",
"keys",
".",
"concat",
"normalize_key",
"(",
"locale",
",",
"separator",
")",
"keys",
".",
"concat",
"normalize_key",
"(",
"scope",
",",
"separator",
")",
"keys",
".",
"concat",
"normalize_key",
"(",
"key",
",",
"separator",
")",
"keys",
"end"
] |
Merges the given locale, key and scope into a single array of keys.
Splits keys that contain dots into multiple keys. Makes sure all
keys are Symbols.
|
[
"Merges",
"the",
"given",
"locale",
"key",
"and",
"scope",
"into",
"a",
"single",
"array",
"of",
"keys",
".",
"Splits",
"keys",
"that",
"contain",
"dots",
"into",
"multiple",
"keys",
".",
"Makes",
"sure",
"all",
"keys",
"are",
"Symbols",
"."
] |
0c5dab494d9b043e00662d8e789229c33045c024
|
https://github.com/ruby-i18n/i18n/blob/0c5dab494d9b043e00662d8e789229c33045c024/lib/i18n.rb#L307-L315
|
12,605
|
ruby-i18n/i18n
|
lib/i18n.rb
|
I18n.Base.enforce_available_locales!
|
def enforce_available_locales!(locale)
if locale != false && config.enforce_available_locales
raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
end
end
|
ruby
|
def enforce_available_locales!(locale)
if locale != false && config.enforce_available_locales
raise I18n::InvalidLocale.new(locale) if !locale_available?(locale)
end
end
|
[
"def",
"enforce_available_locales!",
"(",
"locale",
")",
"if",
"locale",
"!=",
"false",
"&&",
"config",
".",
"enforce_available_locales",
"raise",
"I18n",
"::",
"InvalidLocale",
".",
"new",
"(",
"locale",
")",
"if",
"!",
"locale_available?",
"(",
"locale",
")",
"end",
"end"
] |
Raises an InvalidLocale exception when the passed locale is not available.
|
[
"Raises",
"an",
"InvalidLocale",
"exception",
"when",
"the",
"passed",
"locale",
"is",
"not",
"available",
"."
] |
0c5dab494d9b043e00662d8e789229c33045c024
|
https://github.com/ruby-i18n/i18n/blob/0c5dab494d9b043e00662d8e789229c33045c024/lib/i18n.rb#L324-L328
|
12,606
|
jekyll/jekyll-feed
|
lib/jekyll-feed/generator.rb
|
JekyllFeed.Generator.generate
|
def generate(site)
@site = site
collections.each do |name, meta|
Jekyll.logger.info "Jekyll Feed:", "Generating feed for #{name}"
(meta["categories"] + [nil]).each do |category|
path = feed_path(:collection => name, :category => category)
next if file_exists?(path)
@site.pages << make_page(path, :collection => name, :category => category)
end
end
end
|
ruby
|
def generate(site)
@site = site
collections.each do |name, meta|
Jekyll.logger.info "Jekyll Feed:", "Generating feed for #{name}"
(meta["categories"] + [nil]).each do |category|
path = feed_path(:collection => name, :category => category)
next if file_exists?(path)
@site.pages << make_page(path, :collection => name, :category => category)
end
end
end
|
[
"def",
"generate",
"(",
"site",
")",
"@site",
"=",
"site",
"collections",
".",
"each",
"do",
"|",
"name",
",",
"meta",
"|",
"Jekyll",
".",
"logger",
".",
"info",
"\"Jekyll Feed:\"",
",",
"\"Generating feed for #{name}\"",
"(",
"meta",
"[",
"\"categories\"",
"]",
"+",
"[",
"nil",
"]",
")",
".",
"each",
"do",
"|",
"category",
"|",
"path",
"=",
"feed_path",
"(",
":collection",
"=>",
"name",
",",
":category",
"=>",
"category",
")",
"next",
"if",
"file_exists?",
"(",
"path",
")",
"@site",
".",
"pages",
"<<",
"make_page",
"(",
"path",
",",
":collection",
"=>",
"name",
",",
":category",
"=>",
"category",
")",
"end",
"end",
"end"
] |
Main plugin action, called by Jekyll-core
|
[
"Main",
"plugin",
"action",
"called",
"by",
"Jekyll",
"-",
"core"
] |
6885a7637e40a663667ea4f6399d203b95c2c434
|
https://github.com/jekyll/jekyll-feed/blob/6885a7637e40a663667ea4f6399d203b95c2c434/lib/jekyll-feed/generator.rb#L9-L20
|
12,607
|
jekyll/jekyll-feed
|
lib/jekyll-feed/generator.rb
|
JekyllFeed.Generator.normalize_posts_meta
|
def normalize_posts_meta(hash)
hash["posts"] ||= {}
hash["posts"]["path"] ||= config["path"]
hash["posts"]["categories"] ||= config["categories"]
config["path"] ||= hash["posts"]["path"]
hash
end
|
ruby
|
def normalize_posts_meta(hash)
hash["posts"] ||= {}
hash["posts"]["path"] ||= config["path"]
hash["posts"]["categories"] ||= config["categories"]
config["path"] ||= hash["posts"]["path"]
hash
end
|
[
"def",
"normalize_posts_meta",
"(",
"hash",
")",
"hash",
"[",
"\"posts\"",
"]",
"||=",
"{",
"}",
"hash",
"[",
"\"posts\"",
"]",
"[",
"\"path\"",
"]",
"||=",
"config",
"[",
"\"path\"",
"]",
"hash",
"[",
"\"posts\"",
"]",
"[",
"\"categories\"",
"]",
"||=",
"config",
"[",
"\"categories\"",
"]",
"config",
"[",
"\"path\"",
"]",
"||=",
"hash",
"[",
"\"posts\"",
"]",
"[",
"\"path\"",
"]",
"hash",
"end"
] |
Special case the "posts" collection, which, for ease of use and backwards
compatability, can be configured via top-level keys or directly as a collection
|
[
"Special",
"case",
"the",
"posts",
"collection",
"which",
"for",
"ease",
"of",
"use",
"and",
"backwards",
"compatability",
"can",
"be",
"configured",
"via",
"top",
"-",
"level",
"keys",
"or",
"directly",
"as",
"a",
"collection"
] |
6885a7637e40a663667ea4f6399d203b95c2c434
|
https://github.com/jekyll/jekyll-feed/blob/6885a7637e40a663667ea4f6399d203b95c2c434/lib/jekyll-feed/generator.rb#L104-L110
|
12,608
|
intridea/hashie
|
lib/hashie/rash.rb
|
Hashie.Rash.all
|
def all(query)
return to_enum(:all, query) unless block_given?
if @hash.include? query
yield @hash[query]
return
end
case query
when String
optimize_if_necessary!
# see if any of the regexps match the string
@regexes.each do |regex|
match = regex.match(query)
next unless match
@regex_counts[regex] += 1
value = @hash[regex]
if value.respond_to? :call
yield value.call(match)
else
yield value
end
end
when Numeric
# see if any of the ranges match the integer
@ranges.each do |range|
yield @hash[range] if range.cover? query
end
when Regexp
# Reverse operation: `rash[/regexp/]` returns all the hash's string keys which match the regexp
@hash.each do |key, val|
yield val if key.is_a?(String) && query =~ key
end
end
end
|
ruby
|
def all(query)
return to_enum(:all, query) unless block_given?
if @hash.include? query
yield @hash[query]
return
end
case query
when String
optimize_if_necessary!
# see if any of the regexps match the string
@regexes.each do |regex|
match = regex.match(query)
next unless match
@regex_counts[regex] += 1
value = @hash[regex]
if value.respond_to? :call
yield value.call(match)
else
yield value
end
end
when Numeric
# see if any of the ranges match the integer
@ranges.each do |range|
yield @hash[range] if range.cover? query
end
when Regexp
# Reverse operation: `rash[/regexp/]` returns all the hash's string keys which match the regexp
@hash.each do |key, val|
yield val if key.is_a?(String) && query =~ key
end
end
end
|
[
"def",
"all",
"(",
"query",
")",
"return",
"to_enum",
"(",
":all",
",",
"query",
")",
"unless",
"block_given?",
"if",
"@hash",
".",
"include?",
"query",
"yield",
"@hash",
"[",
"query",
"]",
"return",
"end",
"case",
"query",
"when",
"String",
"optimize_if_necessary!",
"# see if any of the regexps match the string",
"@regexes",
".",
"each",
"do",
"|",
"regex",
"|",
"match",
"=",
"regex",
".",
"match",
"(",
"query",
")",
"next",
"unless",
"match",
"@regex_counts",
"[",
"regex",
"]",
"+=",
"1",
"value",
"=",
"@hash",
"[",
"regex",
"]",
"if",
"value",
".",
"respond_to?",
":call",
"yield",
"value",
".",
"call",
"(",
"match",
")",
"else",
"yield",
"value",
"end",
"end",
"when",
"Numeric",
"# see if any of the ranges match the integer",
"@ranges",
".",
"each",
"do",
"|",
"range",
"|",
"yield",
"@hash",
"[",
"range",
"]",
"if",
"range",
".",
"cover?",
"query",
"end",
"when",
"Regexp",
"# Reverse operation: `rash[/regexp/]` returns all the hash's string keys which match the regexp",
"@hash",
".",
"each",
"do",
"|",
"key",
",",
"val",
"|",
"yield",
"val",
"if",
"key",
".",
"is_a?",
"(",
"String",
")",
"&&",
"query",
"=~",
"key",
"end",
"end",
"end"
] |
Return everything that matches the query.
|
[
"Return",
"everything",
"that",
"matches",
"the",
"query",
"."
] |
da9fd39a0e551e09c1441cb7453c969a4afbfd7f
|
https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/rash.rb#L88-L125
|
12,609
|
intridea/hashie
|
lib/hashie/mash.rb
|
Hashie.Mash.custom_reader
|
def custom_reader(key)
default_proc.call(self, key) if default_proc && !key?(key)
value = regular_reader(convert_key(key))
yield value if block_given?
value
end
|
ruby
|
def custom_reader(key)
default_proc.call(self, key) if default_proc && !key?(key)
value = regular_reader(convert_key(key))
yield value if block_given?
value
end
|
[
"def",
"custom_reader",
"(",
"key",
")",
"default_proc",
".",
"call",
"(",
"self",
",",
"key",
")",
"if",
"default_proc",
"&&",
"!",
"key?",
"(",
"key",
")",
"value",
"=",
"regular_reader",
"(",
"convert_key",
"(",
"key",
")",
")",
"yield",
"value",
"if",
"block_given?",
"value",
"end"
] |
Retrieves an attribute set in the Mash. Will convert
any key passed in to a string before retrieving.
|
[
"Retrieves",
"an",
"attribute",
"set",
"in",
"the",
"Mash",
".",
"Will",
"convert",
"any",
"key",
"passed",
"in",
"to",
"a",
"string",
"before",
"retrieving",
"."
] |
da9fd39a0e551e09c1441cb7453c969a4afbfd7f
|
https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/mash.rb#L144-L149
|
12,610
|
intridea/hashie
|
lib/hashie/mash.rb
|
Hashie.Mash.custom_writer
|
def custom_writer(key, value, convert = true) #:nodoc:
key_as_symbol = (key = convert_key(key)).to_sym
log_built_in_message(key_as_symbol) if log_collision?(key_as_symbol)
regular_writer(key, convert ? convert_value(value) : value)
end
|
ruby
|
def custom_writer(key, value, convert = true) #:nodoc:
key_as_symbol = (key = convert_key(key)).to_sym
log_built_in_message(key_as_symbol) if log_collision?(key_as_symbol)
regular_writer(key, convert ? convert_value(value) : value)
end
|
[
"def",
"custom_writer",
"(",
"key",
",",
"value",
",",
"convert",
"=",
"true",
")",
"#:nodoc:",
"key_as_symbol",
"=",
"(",
"key",
"=",
"convert_key",
"(",
"key",
")",
")",
".",
"to_sym",
"log_built_in_message",
"(",
"key_as_symbol",
")",
"if",
"log_collision?",
"(",
"key_as_symbol",
")",
"regular_writer",
"(",
"key",
",",
"convert",
"?",
"convert_value",
"(",
"value",
")",
":",
"value",
")",
"end"
] |
Sets an attribute in the Mash. Key will be converted to
a string before it is set, and Hashes will be converted
into Mashes for nesting purposes.
|
[
"Sets",
"an",
"attribute",
"in",
"the",
"Mash",
".",
"Key",
"will",
"be",
"converted",
"to",
"a",
"string",
"before",
"it",
"is",
"set",
"and",
"Hashes",
"will",
"be",
"converted",
"into",
"Mashes",
"for",
"nesting",
"purposes",
"."
] |
da9fd39a0e551e09c1441cb7453c969a4afbfd7f
|
https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/mash.rb#L154-L159
|
12,611
|
intridea/hashie
|
lib/hashie/mash.rb
|
Hashie.Mash.initializing_reader
|
def initializing_reader(key)
ck = convert_key(key)
regular_writer(ck, self.class.new) unless key?(ck)
regular_reader(ck)
end
|
ruby
|
def initializing_reader(key)
ck = convert_key(key)
regular_writer(ck, self.class.new) unless key?(ck)
regular_reader(ck)
end
|
[
"def",
"initializing_reader",
"(",
"key",
")",
"ck",
"=",
"convert_key",
"(",
"key",
")",
"regular_writer",
"(",
"ck",
",",
"self",
".",
"class",
".",
"new",
")",
"unless",
"key?",
"(",
"ck",
")",
"regular_reader",
"(",
"ck",
")",
"end"
] |
This is the bang method reader, it will return a new Mash
if there isn't a value already assigned to the key requested.
|
[
"This",
"is",
"the",
"bang",
"method",
"reader",
"it",
"will",
"return",
"a",
"new",
"Mash",
"if",
"there",
"isn",
"t",
"a",
"value",
"already",
"assigned",
"to",
"the",
"key",
"requested",
"."
] |
da9fd39a0e551e09c1441cb7453c969a4afbfd7f
|
https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/mash.rb#L166-L170
|
12,612
|
intridea/hashie
|
lib/hashie/mash.rb
|
Hashie.Mash.underbang_reader
|
def underbang_reader(key)
ck = convert_key(key)
if key?(ck)
regular_reader(ck)
else
self.class.new
end
end
|
ruby
|
def underbang_reader(key)
ck = convert_key(key)
if key?(ck)
regular_reader(ck)
else
self.class.new
end
end
|
[
"def",
"underbang_reader",
"(",
"key",
")",
"ck",
"=",
"convert_key",
"(",
"key",
")",
"if",
"key?",
"(",
"ck",
")",
"regular_reader",
"(",
"ck",
")",
"else",
"self",
".",
"class",
".",
"new",
"end",
"end"
] |
This is the under bang method reader, it will return a temporary new Mash
if there isn't a value already assigned to the key requested.
|
[
"This",
"is",
"the",
"under",
"bang",
"method",
"reader",
"it",
"will",
"return",
"a",
"temporary",
"new",
"Mash",
"if",
"there",
"isn",
"t",
"a",
"value",
"already",
"assigned",
"to",
"the",
"key",
"requested",
"."
] |
da9fd39a0e551e09c1441cb7453c969a4afbfd7f
|
https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/mash.rb#L174-L181
|
12,613
|
intridea/hashie
|
lib/hashie/mash.rb
|
Hashie.Mash.deep_update
|
def deep_update(other_hash, &blk)
other_hash.each_pair do |k, v|
key = convert_key(k)
if v.is_a?(::Hash) && key?(key) && regular_reader(key).is_a?(Mash)
custom_reader(key).deep_update(v, &blk)
else
value = convert_value(v, true)
value = convert_value(yield(key, self[k], value), true) if blk && key?(k)
custom_writer(key, value, false)
end
end
self
end
|
ruby
|
def deep_update(other_hash, &blk)
other_hash.each_pair do |k, v|
key = convert_key(k)
if v.is_a?(::Hash) && key?(key) && regular_reader(key).is_a?(Mash)
custom_reader(key).deep_update(v, &blk)
else
value = convert_value(v, true)
value = convert_value(yield(key, self[k], value), true) if blk && key?(k)
custom_writer(key, value, false)
end
end
self
end
|
[
"def",
"deep_update",
"(",
"other_hash",
",",
"&",
"blk",
")",
"other_hash",
".",
"each_pair",
"do",
"|",
"k",
",",
"v",
"|",
"key",
"=",
"convert_key",
"(",
"k",
")",
"if",
"v",
".",
"is_a?",
"(",
"::",
"Hash",
")",
"&&",
"key?",
"(",
"key",
")",
"&&",
"regular_reader",
"(",
"key",
")",
".",
"is_a?",
"(",
"Mash",
")",
"custom_reader",
"(",
"key",
")",
".",
"deep_update",
"(",
"v",
",",
"blk",
")",
"else",
"value",
"=",
"convert_value",
"(",
"v",
",",
"true",
")",
"value",
"=",
"convert_value",
"(",
"yield",
"(",
"key",
",",
"self",
"[",
"k",
"]",
",",
"value",
")",
",",
"true",
")",
"if",
"blk",
"&&",
"key?",
"(",
"k",
")",
"custom_writer",
"(",
"key",
",",
"value",
",",
"false",
")",
"end",
"end",
"self",
"end"
] |
Recursively merges this mash with the passed
in hash, merging each hash in the hierarchy.
|
[
"Recursively",
"merges",
"this",
"mash",
"with",
"the",
"passed",
"in",
"hash",
"merging",
"each",
"hash",
"in",
"the",
"hierarchy",
"."
] |
da9fd39a0e551e09c1441cb7453c969a4afbfd7f
|
https://github.com/intridea/hashie/blob/da9fd39a0e551e09c1441cb7453c969a4afbfd7f/lib/hashie/mash.rb#L218-L230
|
12,614
|
magnusvk/counter_culture
|
lib/counter_culture/extensions.rb
|
CounterCulture.Extensions._update_counts_after_update
|
def _update_counts_after_update
self.class.after_commit_counter_cache.each do |counter|
# figure out whether the applicable counter cache changed (this can happen
# with dynamic column names)
counter_cache_name_was = counter.counter_cache_name_for(counter.previous_model(self))
counter_cache_name = counter.counter_cache_name_for(self)
if counter.first_level_relation_changed?(self) ||
(counter.delta_column && counter.attribute_changed?(self, counter.delta_column)) ||
counter_cache_name != counter_cache_name_was
# increment the counter cache of the new value
counter.change_counter_cache(self, :increment => true, :counter_column => counter_cache_name)
# decrement the counter cache of the old value
counter.change_counter_cache(self, :increment => false, :was => true, :counter_column => counter_cache_name_was)
end
end
end
|
ruby
|
def _update_counts_after_update
self.class.after_commit_counter_cache.each do |counter|
# figure out whether the applicable counter cache changed (this can happen
# with dynamic column names)
counter_cache_name_was = counter.counter_cache_name_for(counter.previous_model(self))
counter_cache_name = counter.counter_cache_name_for(self)
if counter.first_level_relation_changed?(self) ||
(counter.delta_column && counter.attribute_changed?(self, counter.delta_column)) ||
counter_cache_name != counter_cache_name_was
# increment the counter cache of the new value
counter.change_counter_cache(self, :increment => true, :counter_column => counter_cache_name)
# decrement the counter cache of the old value
counter.change_counter_cache(self, :increment => false, :was => true, :counter_column => counter_cache_name_was)
end
end
end
|
[
"def",
"_update_counts_after_update",
"self",
".",
"class",
".",
"after_commit_counter_cache",
".",
"each",
"do",
"|",
"counter",
"|",
"# figure out whether the applicable counter cache changed (this can happen",
"# with dynamic column names)",
"counter_cache_name_was",
"=",
"counter",
".",
"counter_cache_name_for",
"(",
"counter",
".",
"previous_model",
"(",
"self",
")",
")",
"counter_cache_name",
"=",
"counter",
".",
"counter_cache_name_for",
"(",
"self",
")",
"if",
"counter",
".",
"first_level_relation_changed?",
"(",
"self",
")",
"||",
"(",
"counter",
".",
"delta_column",
"&&",
"counter",
".",
"attribute_changed?",
"(",
"self",
",",
"counter",
".",
"delta_column",
")",
")",
"||",
"counter_cache_name",
"!=",
"counter_cache_name_was",
"# increment the counter cache of the new value",
"counter",
".",
"change_counter_cache",
"(",
"self",
",",
":increment",
"=>",
"true",
",",
":counter_column",
"=>",
"counter_cache_name",
")",
"# decrement the counter cache of the old value",
"counter",
".",
"change_counter_cache",
"(",
"self",
",",
":increment",
"=>",
"false",
",",
":was",
"=>",
"true",
",",
":counter_column",
"=>",
"counter_cache_name_was",
")",
"end",
"end",
"end"
] |
called by after_update callback
|
[
"called",
"by",
"after_update",
"callback"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/extensions.rb#L109-L126
|
12,615
|
magnusvk/counter_culture
|
lib/counter_culture/extensions.rb
|
CounterCulture.Extensions.destroyed_for_counter_culture?
|
def destroyed_for_counter_culture?
if respond_to?(:paranoia_destroyed?)
paranoia_destroyed?
elsif defined?(Discard::Model) && self.class.include?(Discard::Model)
discarded?
else
false
end
end
|
ruby
|
def destroyed_for_counter_culture?
if respond_to?(:paranoia_destroyed?)
paranoia_destroyed?
elsif defined?(Discard::Model) && self.class.include?(Discard::Model)
discarded?
else
false
end
end
|
[
"def",
"destroyed_for_counter_culture?",
"if",
"respond_to?",
"(",
":paranoia_destroyed?",
")",
"paranoia_destroyed?",
"elsif",
"defined?",
"(",
"Discard",
"::",
"Model",
")",
"&&",
"self",
".",
"class",
".",
"include?",
"(",
"Discard",
"::",
"Model",
")",
"discarded?",
"else",
"false",
"end",
"end"
] |
check if record is soft-deleted
|
[
"check",
"if",
"record",
"is",
"soft",
"-",
"deleted"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/extensions.rb#L129-L137
|
12,616
|
magnusvk/counter_culture
|
lib/counter_culture/counter.rb
|
CounterCulture.Counter.change_counter_cache
|
def change_counter_cache(obj, options)
change_counter_column = options.fetch(:counter_column) { counter_cache_name_for(obj) }
# default to the current foreign key value
id_to_change = foreign_key_value(obj, relation, options[:was])
# allow overwriting of foreign key value by the caller
id_to_change = foreign_key_values.call(id_to_change) if foreign_key_values
if id_to_change && change_counter_column
delta_magnitude = if delta_column
(options[:was] ? attribute_was(obj, delta_column) : obj.public_send(delta_column)) || 0
else
counter_delta_magnitude_for(obj)
end
# increment or decrement?
operator = options[:increment] ? '+' : '-'
# we don't use Rails' update_counters because we support changing the timestamp
quoted_column = model.connection.quote_column_name(change_counter_column)
updates = []
# this updates the actual counter
updates << "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{delta_magnitude}"
# and here we update the timestamp, if so desired
if touch
current_time = obj.send(:current_time_from_proper_timezone)
timestamp_columns = obj.send(:timestamp_attributes_for_update_in_model)
timestamp_columns << touch if touch != true
timestamp_columns.each do |timestamp_column|
updates << "#{timestamp_column} = '#{current_time.to_formatted_s(:db)}'"
end
end
klass = relation_klass(relation, source: obj, was: options[:was])
primary_key = relation_primary_key(relation, source: obj, was: options[:was])
if @with_papertrail
instance = klass.where(primary_key => id_to_change).first
if instance
if instance.paper_trail.respond_to?(:save_with_version)
# touch_with_version is deprecated starting in PaperTrail 9.0.0
current_time = obj.send(:current_time_from_proper_timezone)
timestamp_columns = obj.send(:timestamp_attributes_for_update_in_model)
timestamp_columns.each do |timestamp_column|
instance.send("#{timestamp_column}=", current_time)
end
instance.paper_trail.save_with_version(validate: false)
else
instance.paper_trail.touch_with_version
end
end
end
klass.where(primary_key => id_to_change).update_all updates.join(', ')
end
end
|
ruby
|
def change_counter_cache(obj, options)
change_counter_column = options.fetch(:counter_column) { counter_cache_name_for(obj) }
# default to the current foreign key value
id_to_change = foreign_key_value(obj, relation, options[:was])
# allow overwriting of foreign key value by the caller
id_to_change = foreign_key_values.call(id_to_change) if foreign_key_values
if id_to_change && change_counter_column
delta_magnitude = if delta_column
(options[:was] ? attribute_was(obj, delta_column) : obj.public_send(delta_column)) || 0
else
counter_delta_magnitude_for(obj)
end
# increment or decrement?
operator = options[:increment] ? '+' : '-'
# we don't use Rails' update_counters because we support changing the timestamp
quoted_column = model.connection.quote_column_name(change_counter_column)
updates = []
# this updates the actual counter
updates << "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{delta_magnitude}"
# and here we update the timestamp, if so desired
if touch
current_time = obj.send(:current_time_from_proper_timezone)
timestamp_columns = obj.send(:timestamp_attributes_for_update_in_model)
timestamp_columns << touch if touch != true
timestamp_columns.each do |timestamp_column|
updates << "#{timestamp_column} = '#{current_time.to_formatted_s(:db)}'"
end
end
klass = relation_klass(relation, source: obj, was: options[:was])
primary_key = relation_primary_key(relation, source: obj, was: options[:was])
if @with_papertrail
instance = klass.where(primary_key => id_to_change).first
if instance
if instance.paper_trail.respond_to?(:save_with_version)
# touch_with_version is deprecated starting in PaperTrail 9.0.0
current_time = obj.send(:current_time_from_proper_timezone)
timestamp_columns = obj.send(:timestamp_attributes_for_update_in_model)
timestamp_columns.each do |timestamp_column|
instance.send("#{timestamp_column}=", current_time)
end
instance.paper_trail.save_with_version(validate: false)
else
instance.paper_trail.touch_with_version
end
end
end
klass.where(primary_key => id_to_change).update_all updates.join(', ')
end
end
|
[
"def",
"change_counter_cache",
"(",
"obj",
",",
"options",
")",
"change_counter_column",
"=",
"options",
".",
"fetch",
"(",
":counter_column",
")",
"{",
"counter_cache_name_for",
"(",
"obj",
")",
"}",
"# default to the current foreign key value",
"id_to_change",
"=",
"foreign_key_value",
"(",
"obj",
",",
"relation",
",",
"options",
"[",
":was",
"]",
")",
"# allow overwriting of foreign key value by the caller",
"id_to_change",
"=",
"foreign_key_values",
".",
"call",
"(",
"id_to_change",
")",
"if",
"foreign_key_values",
"if",
"id_to_change",
"&&",
"change_counter_column",
"delta_magnitude",
"=",
"if",
"delta_column",
"(",
"options",
"[",
":was",
"]",
"?",
"attribute_was",
"(",
"obj",
",",
"delta_column",
")",
":",
"obj",
".",
"public_send",
"(",
"delta_column",
")",
")",
"||",
"0",
"else",
"counter_delta_magnitude_for",
"(",
"obj",
")",
"end",
"# increment or decrement?",
"operator",
"=",
"options",
"[",
":increment",
"]",
"?",
"'+'",
":",
"'-'",
"# we don't use Rails' update_counters because we support changing the timestamp",
"quoted_column",
"=",
"model",
".",
"connection",
".",
"quote_column_name",
"(",
"change_counter_column",
")",
"updates",
"=",
"[",
"]",
"# this updates the actual counter",
"updates",
"<<",
"\"#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{delta_magnitude}\"",
"# and here we update the timestamp, if so desired",
"if",
"touch",
"current_time",
"=",
"obj",
".",
"send",
"(",
":current_time_from_proper_timezone",
")",
"timestamp_columns",
"=",
"obj",
".",
"send",
"(",
":timestamp_attributes_for_update_in_model",
")",
"timestamp_columns",
"<<",
"touch",
"if",
"touch",
"!=",
"true",
"timestamp_columns",
".",
"each",
"do",
"|",
"timestamp_column",
"|",
"updates",
"<<",
"\"#{timestamp_column} = '#{current_time.to_formatted_s(:db)}'\"",
"end",
"end",
"klass",
"=",
"relation_klass",
"(",
"relation",
",",
"source",
":",
"obj",
",",
"was",
":",
"options",
"[",
":was",
"]",
")",
"primary_key",
"=",
"relation_primary_key",
"(",
"relation",
",",
"source",
":",
"obj",
",",
"was",
":",
"options",
"[",
":was",
"]",
")",
"if",
"@with_papertrail",
"instance",
"=",
"klass",
".",
"where",
"(",
"primary_key",
"=>",
"id_to_change",
")",
".",
"first",
"if",
"instance",
"if",
"instance",
".",
"paper_trail",
".",
"respond_to?",
"(",
":save_with_version",
")",
"# touch_with_version is deprecated starting in PaperTrail 9.0.0",
"current_time",
"=",
"obj",
".",
"send",
"(",
":current_time_from_proper_timezone",
")",
"timestamp_columns",
"=",
"obj",
".",
"send",
"(",
":timestamp_attributes_for_update_in_model",
")",
"timestamp_columns",
".",
"each",
"do",
"|",
"timestamp_column",
"|",
"instance",
".",
"send",
"(",
"\"#{timestamp_column}=\"",
",",
"current_time",
")",
"end",
"instance",
".",
"paper_trail",
".",
"save_with_version",
"(",
"validate",
":",
"false",
")",
"else",
"instance",
".",
"paper_trail",
".",
"touch_with_version",
"end",
"end",
"end",
"klass",
".",
"where",
"(",
"primary_key",
"=>",
"id_to_change",
")",
".",
"update_all",
"updates",
".",
"join",
"(",
"', '",
")",
"end",
"end"
] |
increments or decrements a counter cache
options:
:increment => true to increment, false to decrement
:relation => which relation to increment the count on,
:counter_cache_name => the column name of the counter cache
:counter_column => overrides :counter_cache_name
:delta_column => override the default count delta (1) with the value of this column in the counted record
:was => whether to get the current value or the old value of the
first part of the relation
:with_papertrail => update the column via Papertrail touch_with_version method
|
[
"increments",
"or",
"decrements",
"a",
"counter",
"cache"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/counter.rb#L36-L93
|
12,617
|
magnusvk/counter_culture
|
lib/counter_culture/counter.rb
|
CounterCulture.Counter.foreign_key_value
|
def foreign_key_value(obj, relation, was = false)
relation = relation.is_a?(Enumerable) ? relation.dup : [relation]
first_relation = relation.first
if was
first = relation.shift
foreign_key_value = attribute_was(obj, relation_foreign_key(first))
klass = relation_klass(first, source: obj, was: was)
if foreign_key_value
value = klass.where(
"#{klass.table_name}.#{relation_primary_key(first, source: obj, was: was)} = ?",
foreign_key_value).first
end
else
value = obj
end
while !value.nil? && relation.size > 0
value = value.send(relation.shift)
end
return value.try(relation_primary_key(first_relation, source: obj, was: was).try(:to_sym))
end
|
ruby
|
def foreign_key_value(obj, relation, was = false)
relation = relation.is_a?(Enumerable) ? relation.dup : [relation]
first_relation = relation.first
if was
first = relation.shift
foreign_key_value = attribute_was(obj, relation_foreign_key(first))
klass = relation_klass(first, source: obj, was: was)
if foreign_key_value
value = klass.where(
"#{klass.table_name}.#{relation_primary_key(first, source: obj, was: was)} = ?",
foreign_key_value).first
end
else
value = obj
end
while !value.nil? && relation.size > 0
value = value.send(relation.shift)
end
return value.try(relation_primary_key(first_relation, source: obj, was: was).try(:to_sym))
end
|
[
"def",
"foreign_key_value",
"(",
"obj",
",",
"relation",
",",
"was",
"=",
"false",
")",
"relation",
"=",
"relation",
".",
"is_a?",
"(",
"Enumerable",
")",
"?",
"relation",
".",
"dup",
":",
"[",
"relation",
"]",
"first_relation",
"=",
"relation",
".",
"first",
"if",
"was",
"first",
"=",
"relation",
".",
"shift",
"foreign_key_value",
"=",
"attribute_was",
"(",
"obj",
",",
"relation_foreign_key",
"(",
"first",
")",
")",
"klass",
"=",
"relation_klass",
"(",
"first",
",",
"source",
":",
"obj",
",",
"was",
":",
"was",
")",
"if",
"foreign_key_value",
"value",
"=",
"klass",
".",
"where",
"(",
"\"#{klass.table_name}.#{relation_primary_key(first, source: obj, was: was)} = ?\"",
",",
"foreign_key_value",
")",
".",
"first",
"end",
"else",
"value",
"=",
"obj",
"end",
"while",
"!",
"value",
".",
"nil?",
"&&",
"relation",
".",
"size",
">",
"0",
"value",
"=",
"value",
".",
"send",
"(",
"relation",
".",
"shift",
")",
"end",
"return",
"value",
".",
"try",
"(",
"relation_primary_key",
"(",
"first_relation",
",",
"source",
":",
"obj",
",",
"was",
":",
"was",
")",
".",
"try",
"(",
":to_sym",
")",
")",
"end"
] |
gets the value of the foreign key on the given relation
relation: a symbol or array of symbols; specifies the relation
that has the counter cache column
was: whether to get the current or past value from ActiveRecord;
pass true to get the past value, false or nothing to get the
current value
|
[
"gets",
"the",
"value",
"of",
"the",
"foreign",
"key",
"on",
"the",
"given",
"relation"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/counter.rb#L133-L152
|
12,618
|
magnusvk/counter_culture
|
lib/counter_culture/counter.rb
|
CounterCulture.Counter.relation_reflect
|
def relation_reflect(relation)
relation = relation.is_a?(Enumerable) ? relation.dup : [relation]
# go from one relation to the next until we hit the last reflect object
klass = model
while relation.size > 0
cur_relation = relation.shift
reflect = klass.reflect_on_association(cur_relation)
raise "No relation #{cur_relation} on #{klass.name}" if reflect.nil?
if relation.size > 0
# not necessary to do this at the last link because we won't use
# klass again. not calling this avoids the following causing an
# exception in the now-supported one-level polymorphic counter cache
klass = reflect.klass
end
end
return reflect
end
|
ruby
|
def relation_reflect(relation)
relation = relation.is_a?(Enumerable) ? relation.dup : [relation]
# go from one relation to the next until we hit the last reflect object
klass = model
while relation.size > 0
cur_relation = relation.shift
reflect = klass.reflect_on_association(cur_relation)
raise "No relation #{cur_relation} on #{klass.name}" if reflect.nil?
if relation.size > 0
# not necessary to do this at the last link because we won't use
# klass again. not calling this avoids the following causing an
# exception in the now-supported one-level polymorphic counter cache
klass = reflect.klass
end
end
return reflect
end
|
[
"def",
"relation_reflect",
"(",
"relation",
")",
"relation",
"=",
"relation",
".",
"is_a?",
"(",
"Enumerable",
")",
"?",
"relation",
".",
"dup",
":",
"[",
"relation",
"]",
"# go from one relation to the next until we hit the last reflect object",
"klass",
"=",
"model",
"while",
"relation",
".",
"size",
">",
"0",
"cur_relation",
"=",
"relation",
".",
"shift",
"reflect",
"=",
"klass",
".",
"reflect_on_association",
"(",
"cur_relation",
")",
"raise",
"\"No relation #{cur_relation} on #{klass.name}\"",
"if",
"reflect",
".",
"nil?",
"if",
"relation",
".",
"size",
">",
"0",
"# not necessary to do this at the last link because we won't use",
"# klass again. not calling this avoids the following causing an",
"# exception in the now-supported one-level polymorphic counter cache",
"klass",
"=",
"reflect",
".",
"klass",
"end",
"end",
"return",
"reflect",
"end"
] |
gets the reflect object on the given relation
relation: a symbol or array of symbols; specifies the relation
that has the counter cache column
|
[
"gets",
"the",
"reflect",
"object",
"on",
"the",
"given",
"relation"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/counter.rb#L158-L177
|
12,619
|
magnusvk/counter_culture
|
lib/counter_culture/counter.rb
|
CounterCulture.Counter.relation_klass
|
def relation_klass(relation, source: nil, was: false)
reflect = relation_reflect(relation)
if reflect.options.key?(:polymorphic)
raise "Can't work out relation's class without being passed object (relation: #{relation}, reflect: #{reflect})" if source.nil?
raise "Can't work out polymorhpic relation's class with multiple relations yet" unless (relation.is_a?(Symbol) || relation.length == 1)
# this is the column that stores the polymorphic type, aka the class name
type_column = reflect.foreign_type.to_sym
# so now turn that into the class that we're looking for here
if was
attribute_was(source, type_column).try(:constantize)
else
source.public_send(type_column).try(:constantize)
end
else
reflect.klass
end
end
|
ruby
|
def relation_klass(relation, source: nil, was: false)
reflect = relation_reflect(relation)
if reflect.options.key?(:polymorphic)
raise "Can't work out relation's class without being passed object (relation: #{relation}, reflect: #{reflect})" if source.nil?
raise "Can't work out polymorhpic relation's class with multiple relations yet" unless (relation.is_a?(Symbol) || relation.length == 1)
# this is the column that stores the polymorphic type, aka the class name
type_column = reflect.foreign_type.to_sym
# so now turn that into the class that we're looking for here
if was
attribute_was(source, type_column).try(:constantize)
else
source.public_send(type_column).try(:constantize)
end
else
reflect.klass
end
end
|
[
"def",
"relation_klass",
"(",
"relation",
",",
"source",
":",
"nil",
",",
"was",
":",
"false",
")",
"reflect",
"=",
"relation_reflect",
"(",
"relation",
")",
"if",
"reflect",
".",
"options",
".",
"key?",
"(",
":polymorphic",
")",
"raise",
"\"Can't work out relation's class without being passed object (relation: #{relation}, reflect: #{reflect})\"",
"if",
"source",
".",
"nil?",
"raise",
"\"Can't work out polymorhpic relation's class with multiple relations yet\"",
"unless",
"(",
"relation",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"relation",
".",
"length",
"==",
"1",
")",
"# this is the column that stores the polymorphic type, aka the class name",
"type_column",
"=",
"reflect",
".",
"foreign_type",
".",
"to_sym",
"# so now turn that into the class that we're looking for here",
"if",
"was",
"attribute_was",
"(",
"source",
",",
"type_column",
")",
".",
"try",
"(",
":constantize",
")",
"else",
"source",
".",
"public_send",
"(",
"type_column",
")",
".",
"try",
"(",
":constantize",
")",
"end",
"else",
"reflect",
".",
"klass",
"end",
"end"
] |
gets the class of the given relation
relation: a symbol or array of symbols; specifies the relation
that has the counter cache column
source [optional]: the source object,
only needed for polymorphic associations,
probably only works with a single relation (symbol, or array of 1 symbol)
was: boolean
we're actually looking for the old value -- only can change for polymorphic relations
|
[
"gets",
"the",
"class",
"of",
"the",
"given",
"relation"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/counter.rb#L188-L204
|
12,620
|
magnusvk/counter_culture
|
lib/counter_culture/counter.rb
|
CounterCulture.Counter.relation_primary_key
|
def relation_primary_key(relation, source: nil, was: false)
reflect = relation_reflect(relation)
klass = nil
if reflect.options.key?(:polymorphic)
raise "can't handle multiple keys with polymorphic associations" unless (relation.is_a?(Symbol) || relation.length == 1)
raise "must specify source for polymorphic associations..." unless source
return relation_klass(relation, source: source, was: was).try(:primary_key)
end
reflect.association_primary_key(klass)
end
|
ruby
|
def relation_primary_key(relation, source: nil, was: false)
reflect = relation_reflect(relation)
klass = nil
if reflect.options.key?(:polymorphic)
raise "can't handle multiple keys with polymorphic associations" unless (relation.is_a?(Symbol) || relation.length == 1)
raise "must specify source for polymorphic associations..." unless source
return relation_klass(relation, source: source, was: was).try(:primary_key)
end
reflect.association_primary_key(klass)
end
|
[
"def",
"relation_primary_key",
"(",
"relation",
",",
"source",
":",
"nil",
",",
"was",
":",
"false",
")",
"reflect",
"=",
"relation_reflect",
"(",
"relation",
")",
"klass",
"=",
"nil",
"if",
"reflect",
".",
"options",
".",
"key?",
"(",
":polymorphic",
")",
"raise",
"\"can't handle multiple keys with polymorphic associations\"",
"unless",
"(",
"relation",
".",
"is_a?",
"(",
"Symbol",
")",
"||",
"relation",
".",
"length",
"==",
"1",
")",
"raise",
"\"must specify source for polymorphic associations...\"",
"unless",
"source",
"return",
"relation_klass",
"(",
"relation",
",",
"source",
":",
"source",
",",
"was",
":",
"was",
")",
".",
"try",
"(",
":primary_key",
")",
"end",
"reflect",
".",
"association_primary_key",
"(",
"klass",
")",
"end"
] |
gets the primary key name of the given relation
relation: a symbol or array of symbols; specifies the relation
that has the counter cache column
source[optional]: the model instance that the relationship is linked from,
only needed for polymorphic associations,
probably only works with a single relation (symbol, or array of 1 symbol)
was: boolean
we're actually looking for the old value -- only can change for polymorphic relations
|
[
"gets",
"the",
"primary",
"key",
"name",
"of",
"the",
"given",
"relation"
] |
6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba
|
https://github.com/magnusvk/counter_culture/blob/6b5bd4d6e1ee4f10f262ace7cfed5776af9520ba/lib/counter_culture/counter.rb#L247-L256
|
12,621
|
tomiacannondale/era_ja
|
lib/era_ja/conversion.rb
|
EraJa.Conversion.to_era
|
def to_era(format = "%o%E.%m.%d", era_names: ERA_NAME_DEFAULTS)
raise EraJa::DateOutOfRangeError unless era_convertible?
@era_format = format.gsub(/%J/, "%J%")
str_time = strftime(@era_format)
if @era_format =~ /%([EOo]|1O)/
case
when self.to_time < ::Time.mktime(1912,7,30)
str_time = era_year(year - 1867, :meiji, era_names)
when self.to_time < ::Time.mktime(1926,12,25)
str_time = era_year(year - 1911, :taisho, era_names)
when self.to_time < ::Time.mktime(1989,1,8)
str_time = era_year(year - 1925, :showa, era_names)
when self.to_time < ::Time.mktime(2019, 5, 1)
str_time = era_year(year - 1988, :heisei, era_names)
else
str_time = era_year(year - 2018, :reiwa, era_names)
end
end
str_time.gsub(/%J(\d+)/) { to_kanzi($1) }
end
|
ruby
|
def to_era(format = "%o%E.%m.%d", era_names: ERA_NAME_DEFAULTS)
raise EraJa::DateOutOfRangeError unless era_convertible?
@era_format = format.gsub(/%J/, "%J%")
str_time = strftime(@era_format)
if @era_format =~ /%([EOo]|1O)/
case
when self.to_time < ::Time.mktime(1912,7,30)
str_time = era_year(year - 1867, :meiji, era_names)
when self.to_time < ::Time.mktime(1926,12,25)
str_time = era_year(year - 1911, :taisho, era_names)
when self.to_time < ::Time.mktime(1989,1,8)
str_time = era_year(year - 1925, :showa, era_names)
when self.to_time < ::Time.mktime(2019, 5, 1)
str_time = era_year(year - 1988, :heisei, era_names)
else
str_time = era_year(year - 2018, :reiwa, era_names)
end
end
str_time.gsub(/%J(\d+)/) { to_kanzi($1) }
end
|
[
"def",
"to_era",
"(",
"format",
"=",
"\"%o%E.%m.%d\"",
",",
"era_names",
":",
"ERA_NAME_DEFAULTS",
")",
"raise",
"EraJa",
"::",
"DateOutOfRangeError",
"unless",
"era_convertible?",
"@era_format",
"=",
"format",
".",
"gsub",
"(",
"/",
"/",
",",
"\"%J%\"",
")",
"str_time",
"=",
"strftime",
"(",
"@era_format",
")",
"if",
"@era_format",
"=~",
"/",
"/",
"case",
"when",
"self",
".",
"to_time",
"<",
"::",
"Time",
".",
"mktime",
"(",
"1912",
",",
"7",
",",
"30",
")",
"str_time",
"=",
"era_year",
"(",
"year",
"-",
"1867",
",",
":meiji",
",",
"era_names",
")",
"when",
"self",
".",
"to_time",
"<",
"::",
"Time",
".",
"mktime",
"(",
"1926",
",",
"12",
",",
"25",
")",
"str_time",
"=",
"era_year",
"(",
"year",
"-",
"1911",
",",
":taisho",
",",
"era_names",
")",
"when",
"self",
".",
"to_time",
"<",
"::",
"Time",
".",
"mktime",
"(",
"1989",
",",
"1",
",",
"8",
")",
"str_time",
"=",
"era_year",
"(",
"year",
"-",
"1925",
",",
":showa",
",",
"era_names",
")",
"when",
"self",
".",
"to_time",
"<",
"::",
"Time",
".",
"mktime",
"(",
"2019",
",",
"5",
",",
"1",
")",
"str_time",
"=",
"era_year",
"(",
"year",
"-",
"1988",
",",
":heisei",
",",
"era_names",
")",
"else",
"str_time",
"=",
"era_year",
"(",
"year",
"-",
"2018",
",",
":reiwa",
",",
"era_names",
")",
"end",
"end",
"str_time",
".",
"gsub",
"(",
"/",
"\\d",
"/",
")",
"{",
"to_kanzi",
"(",
"$1",
")",
"}",
"end"
] |
Convert to Japanese era.
@param [String] format_string
Time#strftime format string can be used
#### extra format string
* %o - era(alphabet)
* %O - era(kanzi)
* %E - era year
* %J - kanzi number
@param [Hash] era_names
If you want to convert custom to era strings (eg `平`, `h`), you can set this argument.
key is `:meiji' or `:taisho' or `:showa` or `:heisei` or `:reiwa`.
value is ["alphabet era name"(ex `h`, `s`)(related to `%o`), "multibyte era name"(eg `平`, `昭`)(related to `%O`)].
this argument is same as one element of ERA_NAME_DEFAULTS.
@return [String]
|
[
"Convert",
"to",
"Japanese",
"era",
"."
] |
1ec1b7e1b53caf4290c755967f180719db944d50
|
https://github.com/tomiacannondale/era_ja/blob/1ec1b7e1b53caf4290c755967f180719db944d50/lib/era_ja/conversion.rb#L28-L48
|
12,622
|
Chris911/iStats
|
lib/iStats/utils.rb
|
IStats.Utils.abs_thresholds
|
def abs_thresholds(scale, max_value)
at = []
scale.each { |v|
at.push(v * max_value)
}
return at
end
|
ruby
|
def abs_thresholds(scale, max_value)
at = []
scale.each { |v|
at.push(v * max_value)
}
return at
end
|
[
"def",
"abs_thresholds",
"(",
"scale",
",",
"max_value",
")",
"at",
"=",
"[",
"]",
"scale",
".",
"each",
"{",
"|",
"v",
"|",
"at",
".",
"push",
"(",
"v",
"*",
"max_value",
")",
"}",
"return",
"at",
"end"
] |
Produce a thresholds array containing absolute values based on supplied
percentages applied to a literal max value.
|
[
"Produce",
"a",
"thresholds",
"array",
"containing",
"absolute",
"values",
"based",
"on",
"supplied",
"percentages",
"applied",
"to",
"a",
"literal",
"max",
"value",
"."
] |
0b86af356baa680cabc5665cc0364de29f1f5958
|
https://github.com/Chris911/iStats/blob/0b86af356baa680cabc5665cc0364de29f1f5958/lib/iStats/utils.rb#L15-L21
|
12,623
|
benbalter/word-to-markdown
|
lib/cliver/dependency_ext.rb
|
Cliver.Dependency.open?
|
def open?
ProcTable.ps.any? { |p| p.comm == path }
# See https://github.com/djberg96/sys-proctable/issues/44
rescue ArgumentError
false
end
|
ruby
|
def open?
ProcTable.ps.any? { |p| p.comm == path }
# See https://github.com/djberg96/sys-proctable/issues/44
rescue ArgumentError
false
end
|
[
"def",
"open?",
"ProcTable",
".",
"ps",
".",
"any?",
"{",
"|",
"p",
"|",
"p",
".",
"comm",
"==",
"path",
"}",
"# See https://github.com/djberg96/sys-proctable/issues/44",
"rescue",
"ArgumentError",
"false",
"end"
] |
Is the detected dependency currently open?
|
[
"Is",
"the",
"detected",
"dependency",
"currently",
"open?"
] |
48031ffd70c9a8caa9978fa576c6de24b736df20
|
https://github.com/benbalter/word-to-markdown/blob/48031ffd70c9a8caa9978fa576c6de24b736df20/lib/cliver/dependency_ext.rb#L18-L23
|
12,624
|
googleapis/google-auth-library-ruby
|
lib/googleauth/application_default.rb
|
Google.Auth.get_application_default
|
def get_application_default scope = nil, options = {}
creds = DefaultCredentials.from_env(scope, options) ||
DefaultCredentials.from_well_known_path(scope, options) ||
DefaultCredentials.from_system_default_path(scope, options)
return creds unless creds.nil?
unless GCECredentials.on_gce? options
# Clear cache of the result of GCECredentials.on_gce?
GCECredentials.unmemoize_all
raise NOT_FOUND_ERROR
end
GCECredentials.new
end
|
ruby
|
def get_application_default scope = nil, options = {}
creds = DefaultCredentials.from_env(scope, options) ||
DefaultCredentials.from_well_known_path(scope, options) ||
DefaultCredentials.from_system_default_path(scope, options)
return creds unless creds.nil?
unless GCECredentials.on_gce? options
# Clear cache of the result of GCECredentials.on_gce?
GCECredentials.unmemoize_all
raise NOT_FOUND_ERROR
end
GCECredentials.new
end
|
[
"def",
"get_application_default",
"scope",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
"creds",
"=",
"DefaultCredentials",
".",
"from_env",
"(",
"scope",
",",
"options",
")",
"||",
"DefaultCredentials",
".",
"from_well_known_path",
"(",
"scope",
",",
"options",
")",
"||",
"DefaultCredentials",
".",
"from_system_default_path",
"(",
"scope",
",",
"options",
")",
"return",
"creds",
"unless",
"creds",
".",
"nil?",
"unless",
"GCECredentials",
".",
"on_gce?",
"options",
"# Clear cache of the result of GCECredentials.on_gce?",
"GCECredentials",
".",
"unmemoize_all",
"raise",
"NOT_FOUND_ERROR",
"end",
"GCECredentials",
".",
"new",
"end"
] |
Obtains the default credentials implementation to use in this
environment.
Use this to obtain the Application Default Credentials for accessing
Google APIs. Application Default Credentials are described in detail
at http://goo.gl/IUuyuX.
If supplied, scope is used to create the credentials instance, when it can
be applied. E.g, on google compute engine and for user credentials the
scope is ignored.
@param scope [string|array|nil] the scope(s) to access
@param options [Hash] Connection options. These may be used to configure
the `Faraday::Connection` used for outgoing HTTP requests. For
example, if a connection proxy must be used in the current network,
you may provide a connection with with the needed proxy options.
The following keys are recognized:
* `:default_connection` The connection object to use for token
refresh requests.
* `:connection_builder` A `Proc` that creates and returns a
connection to use for token refresh requests.
* `:connection` The connection to use to determine whether GCE
metadata credentials are available.
|
[
"Obtains",
"the",
"default",
"credentials",
"implementation",
"to",
"use",
"in",
"this",
"environment",
"."
] |
f6e8355edd19be17406b052ac1c64d3a595768e8
|
https://github.com/googleapis/google-auth-library-ruby/blob/f6e8355edd19be17406b052ac1c64d3a595768e8/lib/googleauth/application_default.rb#L68-L79
|
12,625
|
rails/sprockets
|
lib/sprockets/directive_processor.rb
|
Sprockets.DirectiveProcessor.extract_directives
|
def extract_directives(header)
processed_header = String.new("")
directives = []
header.lines.each_with_index do |line, index|
if directive = line[DIRECTIVE_PATTERN, 1]
name, *args = Shellwords.shellwords(directive)
if respond_to?("process_#{name}_directive", true)
directives << [index + 1, name, *args]
# Replace directive line with a clean break
line = "\n"
end
end
processed_header << line
end
processed_header.chomp!
# Ensure header ends in a new line like before it was processed
processed_header << "\n" if processed_header.length > 0 && header[-1] == "\n"
return processed_header, directives
end
|
ruby
|
def extract_directives(header)
processed_header = String.new("")
directives = []
header.lines.each_with_index do |line, index|
if directive = line[DIRECTIVE_PATTERN, 1]
name, *args = Shellwords.shellwords(directive)
if respond_to?("process_#{name}_directive", true)
directives << [index + 1, name, *args]
# Replace directive line with a clean break
line = "\n"
end
end
processed_header << line
end
processed_header.chomp!
# Ensure header ends in a new line like before it was processed
processed_header << "\n" if processed_header.length > 0 && header[-1] == "\n"
return processed_header, directives
end
|
[
"def",
"extract_directives",
"(",
"header",
")",
"processed_header",
"=",
"String",
".",
"new",
"(",
"\"\"",
")",
"directives",
"=",
"[",
"]",
"header",
".",
"lines",
".",
"each_with_index",
"do",
"|",
"line",
",",
"index",
"|",
"if",
"directive",
"=",
"line",
"[",
"DIRECTIVE_PATTERN",
",",
"1",
"]",
"name",
",",
"*",
"args",
"=",
"Shellwords",
".",
"shellwords",
"(",
"directive",
")",
"if",
"respond_to?",
"(",
"\"process_#{name}_directive\"",
",",
"true",
")",
"directives",
"<<",
"[",
"index",
"+",
"1",
",",
"name",
",",
"args",
"]",
"# Replace directive line with a clean break",
"line",
"=",
"\"\\n\"",
"end",
"end",
"processed_header",
"<<",
"line",
"end",
"processed_header",
".",
"chomp!",
"# Ensure header ends in a new line like before it was processed",
"processed_header",
"<<",
"\"\\n\"",
"if",
"processed_header",
".",
"length",
">",
"0",
"&&",
"header",
"[",
"-",
"1",
"]",
"==",
"\"\\n\"",
"return",
"processed_header",
",",
"directives",
"end"
] |
Returns an Array of directive structures. Each structure
is an Array with the line number as the first element, the
directive name as the second element, followed by any
arguments.
[[1, "require", "foo"], [2, "require", "bar"]]
|
[
"Returns",
"an",
"Array",
"of",
"directive",
"structures",
".",
"Each",
"structure",
"is",
"an",
"Array",
"with",
"the",
"line",
"number",
"as",
"the",
"first",
"element",
"the",
"directive",
"name",
"as",
"the",
"second",
"element",
"followed",
"by",
"any",
"arguments",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/directive_processor.rb#L141-L162
|
12,626
|
rails/sprockets
|
lib/rake/sprocketstask.rb
|
Rake.SprocketsTask.log_level=
|
def log_level=(level)
if level.is_a?(Integer)
@logger.level = level
else
@logger.level = Logger.const_get(level.to_s.upcase)
end
end
|
ruby
|
def log_level=(level)
if level.is_a?(Integer)
@logger.level = level
else
@logger.level = Logger.const_get(level.to_s.upcase)
end
end
|
[
"def",
"log_level",
"=",
"(",
"level",
")",
"if",
"level",
".",
"is_a?",
"(",
"Integer",
")",
"@logger",
".",
"level",
"=",
"level",
"else",
"@logger",
".",
"level",
"=",
"Logger",
".",
"const_get",
"(",
"level",
".",
"to_s",
".",
"upcase",
")",
"end",
"end"
] |
Set logger level with constant or symbol.
t.log_level = Logger::INFO
t.log_level = :debug
|
[
"Set",
"logger",
"level",
"with",
"constant",
"or",
"symbol",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/rake/sprocketstask.rb#L91-L97
|
12,627
|
rails/sprockets
|
lib/rake/sprocketstask.rb
|
Rake.SprocketsTask.with_logger
|
def with_logger
if env = manifest.environment
old_logger = env.logger
env.logger = @logger
end
yield
ensure
env.logger = old_logger if env
end
|
ruby
|
def with_logger
if env = manifest.environment
old_logger = env.logger
env.logger = @logger
end
yield
ensure
env.logger = old_logger if env
end
|
[
"def",
"with_logger",
"if",
"env",
"=",
"manifest",
".",
"environment",
"old_logger",
"=",
"env",
".",
"logger",
"env",
".",
"logger",
"=",
"@logger",
"end",
"yield",
"ensure",
"env",
".",
"logger",
"=",
"old_logger",
"if",
"env",
"end"
] |
Sub out environment logger with our rake task logger that
writes to stderr.
|
[
"Sub",
"out",
"environment",
"logger",
"with",
"our",
"rake",
"task",
"logger",
"that",
"writes",
"to",
"stderr",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/rake/sprocketstask.rb#L143-L151
|
12,628
|
rails/sprockets
|
lib/sprockets/processing.rb
|
Sprockets.Processing.register_pipeline
|
def register_pipeline(name, proc = nil, &block)
proc ||= block
self.config = hash_reassoc(config, :pipeline_exts) do |pipeline_exts|
pipeline_exts.merge(".#{name}".freeze => name.to_sym)
end
self.config = hash_reassoc(config, :pipelines) do |pipelines|
pipelines.merge(name.to_sym => proc)
end
end
|
ruby
|
def register_pipeline(name, proc = nil, &block)
proc ||= block
self.config = hash_reassoc(config, :pipeline_exts) do |pipeline_exts|
pipeline_exts.merge(".#{name}".freeze => name.to_sym)
end
self.config = hash_reassoc(config, :pipelines) do |pipelines|
pipelines.merge(name.to_sym => proc)
end
end
|
[
"def",
"register_pipeline",
"(",
"name",
",",
"proc",
"=",
"nil",
",",
"&",
"block",
")",
"proc",
"||=",
"block",
"self",
".",
"config",
"=",
"hash_reassoc",
"(",
"config",
",",
":pipeline_exts",
")",
"do",
"|",
"pipeline_exts",
"|",
"pipeline_exts",
".",
"merge",
"(",
"\".#{name}\"",
".",
"freeze",
"=>",
"name",
".",
"to_sym",
")",
"end",
"self",
".",
"config",
"=",
"hash_reassoc",
"(",
"config",
",",
":pipelines",
")",
"do",
"|",
"pipelines",
"|",
"pipelines",
".",
"merge",
"(",
"name",
".",
"to_sym",
"=>",
"proc",
")",
"end",
"end"
] |
Registers a pipeline that will be called by `call_processor` method.
|
[
"Registers",
"a",
"pipeline",
"that",
"will",
"be",
"called",
"by",
"call_processor",
"method",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/processing.rb#L19-L29
|
12,629
|
rails/sprockets
|
lib/sprockets/paths.rb
|
Sprockets.Paths.prepend_path
|
def prepend_path(path)
self.config = hash_reassoc(config, :paths) do |paths|
path = File.expand_path(path, config[:root]).freeze
paths.unshift(path)
end
end
|
ruby
|
def prepend_path(path)
self.config = hash_reassoc(config, :paths) do |paths|
path = File.expand_path(path, config[:root]).freeze
paths.unshift(path)
end
end
|
[
"def",
"prepend_path",
"(",
"path",
")",
"self",
".",
"config",
"=",
"hash_reassoc",
"(",
"config",
",",
":paths",
")",
"do",
"|",
"paths",
"|",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
",",
"config",
"[",
":root",
"]",
")",
".",
"freeze",
"paths",
".",
"unshift",
"(",
"path",
")",
"end",
"end"
] |
Prepend a `path` to the `paths` list.
Paths at the end of the `Array` have the least priority.
|
[
"Prepend",
"a",
"path",
"to",
"the",
"paths",
"list",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/paths.rb#L37-L42
|
12,630
|
rails/sprockets
|
lib/sprockets/paths.rb
|
Sprockets.Paths.append_path
|
def append_path(path)
self.config = hash_reassoc(config, :paths) do |paths|
path = File.expand_path(path, config[:root]).freeze
paths.push(path)
end
end
|
ruby
|
def append_path(path)
self.config = hash_reassoc(config, :paths) do |paths|
path = File.expand_path(path, config[:root]).freeze
paths.push(path)
end
end
|
[
"def",
"append_path",
"(",
"path",
")",
"self",
".",
"config",
"=",
"hash_reassoc",
"(",
"config",
",",
":paths",
")",
"do",
"|",
"paths",
"|",
"path",
"=",
"File",
".",
"expand_path",
"(",
"path",
",",
"config",
"[",
":root",
"]",
")",
".",
"freeze",
"paths",
".",
"push",
"(",
"path",
")",
"end",
"end"
] |
Append a `path` to the `paths` list.
Paths at the beginning of the `Array` have a higher priority.
|
[
"Append",
"a",
"path",
"to",
"the",
"paths",
"list",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/paths.rb#L47-L52
|
12,631
|
rails/sprockets
|
lib/sprockets/context.rb
|
Sprockets.Context.depend_on
|
def depend_on(path)
if environment.absolute_path?(path) && environment.stat(path)
@dependencies << environment.build_file_digest_uri(path)
else
resolve(path)
end
nil
end
|
ruby
|
def depend_on(path)
if environment.absolute_path?(path) && environment.stat(path)
@dependencies << environment.build_file_digest_uri(path)
else
resolve(path)
end
nil
end
|
[
"def",
"depend_on",
"(",
"path",
")",
"if",
"environment",
".",
"absolute_path?",
"(",
"path",
")",
"&&",
"environment",
".",
"stat",
"(",
"path",
")",
"@dependencies",
"<<",
"environment",
".",
"build_file_digest_uri",
"(",
"path",
")",
"else",
"resolve",
"(",
"path",
")",
"end",
"nil",
"end"
] |
`depend_on` allows you to state a dependency on a file without
including it.
This is used for caching purposes. Any changes made to
the dependency file will invalidate the cache of the
source file.
|
[
"depend_on",
"allows",
"you",
"to",
"state",
"a",
"dependency",
"on",
"a",
"file",
"without",
"including",
"it",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/context.rb#L127-L134
|
12,632
|
rails/sprockets
|
lib/sprockets/context.rb
|
Sprockets.Context.base64_asset_data_uri
|
def base64_asset_data_uri(asset)
data = Rack::Utils.escape(EncodingUtils.base64(asset.source))
"data:#{asset.content_type};base64,#{data}"
end
|
ruby
|
def base64_asset_data_uri(asset)
data = Rack::Utils.escape(EncodingUtils.base64(asset.source))
"data:#{asset.content_type};base64,#{data}"
end
|
[
"def",
"base64_asset_data_uri",
"(",
"asset",
")",
"data",
"=",
"Rack",
"::",
"Utils",
".",
"escape",
"(",
"EncodingUtils",
".",
"base64",
"(",
"asset",
".",
"source",
")",
")",
"\"data:#{asset.content_type};base64,#{data}\"",
"end"
] |
Returns a Base64-encoded data URI.
|
[
"Returns",
"a",
"Base64",
"-",
"encoded",
"data",
"URI",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/context.rb#L271-L274
|
12,633
|
rails/sprockets
|
lib/sprockets/context.rb
|
Sprockets.Context.optimize_svg_for_uri_escaping!
|
def optimize_svg_for_uri_escaping!(svg)
# Remove comments, xml meta, and doctype
svg.gsub!(/<!--.*?-->|<\?.*?\?>|<!.*?>/m, '')
# Replace consecutive whitespace and newlines with a space
svg.gsub!(/\s+/, ' ')
# Collapse inter-tag whitespace
svg.gsub!('> <', '><')
# Replace " with '
svg.gsub!(/([\w:])="(.*?)"/, "\\1='\\2'")
svg.strip!
end
|
ruby
|
def optimize_svg_for_uri_escaping!(svg)
# Remove comments, xml meta, and doctype
svg.gsub!(/<!--.*?-->|<\?.*?\?>|<!.*?>/m, '')
# Replace consecutive whitespace and newlines with a space
svg.gsub!(/\s+/, ' ')
# Collapse inter-tag whitespace
svg.gsub!('> <', '><')
# Replace " with '
svg.gsub!(/([\w:])="(.*?)"/, "\\1='\\2'")
svg.strip!
end
|
[
"def",
"optimize_svg_for_uri_escaping!",
"(",
"svg",
")",
"# Remove comments, xml meta, and doctype",
"svg",
".",
"gsub!",
"(",
"/",
"\\?",
"\\?",
"/m",
",",
"''",
")",
"# Replace consecutive whitespace and newlines with a space",
"svg",
".",
"gsub!",
"(",
"/",
"\\s",
"/",
",",
"' '",
")",
"# Collapse inter-tag whitespace",
"svg",
".",
"gsub!",
"(",
"'> <'",
",",
"'><'",
")",
"# Replace \" with '",
"svg",
".",
"gsub!",
"(",
"/",
"\\w",
"/",
",",
"\"\\\\1='\\\\2'\"",
")",
"svg",
".",
"strip!",
"end"
] |
Optimizes an SVG for being URI-escaped.
This method only performs these basic but crucial optimizations:
* Replaces " with ', because ' does not need escaping.
* Removes comments, meta, doctype, and newlines.
* Collapses whitespace.
|
[
"Optimizes",
"an",
"SVG",
"for",
"being",
"URI",
"-",
"escaped",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/context.rb#L282-L292
|
12,634
|
rails/sprockets
|
lib/sprockets/context.rb
|
Sprockets.Context.optimize_quoted_uri_escapes!
|
def optimize_quoted_uri_escapes!(escaped)
escaped.gsub!('%3D', '=')
escaped.gsub!('%3A', ':')
escaped.gsub!('%2F', '/')
escaped.gsub!('%27', "'")
escaped.tr!('+', ' ')
end
|
ruby
|
def optimize_quoted_uri_escapes!(escaped)
escaped.gsub!('%3D', '=')
escaped.gsub!('%3A', ':')
escaped.gsub!('%2F', '/')
escaped.gsub!('%27', "'")
escaped.tr!('+', ' ')
end
|
[
"def",
"optimize_quoted_uri_escapes!",
"(",
"escaped",
")",
"escaped",
".",
"gsub!",
"(",
"'%3D'",
",",
"'='",
")",
"escaped",
".",
"gsub!",
"(",
"'%3A'",
",",
"':'",
")",
"escaped",
".",
"gsub!",
"(",
"'%2F'",
",",
"'/'",
")",
"escaped",
".",
"gsub!",
"(",
"'%27'",
",",
"\"'\"",
")",
"escaped",
".",
"tr!",
"(",
"'+'",
",",
"' '",
")",
"end"
] |
Un-escapes characters in the given URI-escaped string that do not need
escaping in "-quoted data URIs.
|
[
"Un",
"-",
"escapes",
"characters",
"in",
"the",
"given",
"URI",
"-",
"escaped",
"string",
"that",
"do",
"not",
"need",
"escaping",
"in",
"-",
"quoted",
"data",
"URIs",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/context.rb#L296-L302
|
12,635
|
rails/sprockets
|
lib/sprockets/manifest.rb
|
Sprockets.Manifest.compile
|
def compile(*args)
unless environment
raise Error, "manifest requires environment for compilation"
end
filenames = []
concurrent_exporters = []
assets_to_export = Concurrent::Array.new
find(*args) do |asset|
assets_to_export << asset
end
assets_to_export.each do |asset|
mtime = Time.now.iso8601
files[asset.digest_path] = {
'logical_path' => asset.logical_path,
'mtime' => mtime,
'size' => asset.bytesize,
'digest' => asset.hexdigest,
# Deprecated: Remove beta integrity attribute in next release.
# Callers should DigestUtils.hexdigest_integrity_uri to compute the
# digest themselves.
'integrity' => DigestUtils.hexdigest_integrity_uri(asset.hexdigest)
}
assets[asset.logical_path] = asset.digest_path
filenames << asset.filename
promise = nil
exporters_for_asset(asset) do |exporter|
next if exporter.skip?(logger)
if promise.nil?
promise = Concurrent::Promise.new(executor: executor) { exporter.call }
concurrent_exporters << promise.execute
else
concurrent_exporters << promise.then { exporter.call }
end
end
end
# make sure all exporters have finished before returning the main thread
concurrent_exporters.each(&:wait!)
save
filenames
end
|
ruby
|
def compile(*args)
unless environment
raise Error, "manifest requires environment for compilation"
end
filenames = []
concurrent_exporters = []
assets_to_export = Concurrent::Array.new
find(*args) do |asset|
assets_to_export << asset
end
assets_to_export.each do |asset|
mtime = Time.now.iso8601
files[asset.digest_path] = {
'logical_path' => asset.logical_path,
'mtime' => mtime,
'size' => asset.bytesize,
'digest' => asset.hexdigest,
# Deprecated: Remove beta integrity attribute in next release.
# Callers should DigestUtils.hexdigest_integrity_uri to compute the
# digest themselves.
'integrity' => DigestUtils.hexdigest_integrity_uri(asset.hexdigest)
}
assets[asset.logical_path] = asset.digest_path
filenames << asset.filename
promise = nil
exporters_for_asset(asset) do |exporter|
next if exporter.skip?(logger)
if promise.nil?
promise = Concurrent::Promise.new(executor: executor) { exporter.call }
concurrent_exporters << promise.execute
else
concurrent_exporters << promise.then { exporter.call }
end
end
end
# make sure all exporters have finished before returning the main thread
concurrent_exporters.each(&:wait!)
save
filenames
end
|
[
"def",
"compile",
"(",
"*",
"args",
")",
"unless",
"environment",
"raise",
"Error",
",",
"\"manifest requires environment for compilation\"",
"end",
"filenames",
"=",
"[",
"]",
"concurrent_exporters",
"=",
"[",
"]",
"assets_to_export",
"=",
"Concurrent",
"::",
"Array",
".",
"new",
"find",
"(",
"args",
")",
"do",
"|",
"asset",
"|",
"assets_to_export",
"<<",
"asset",
"end",
"assets_to_export",
".",
"each",
"do",
"|",
"asset",
"|",
"mtime",
"=",
"Time",
".",
"now",
".",
"iso8601",
"files",
"[",
"asset",
".",
"digest_path",
"]",
"=",
"{",
"'logical_path'",
"=>",
"asset",
".",
"logical_path",
",",
"'mtime'",
"=>",
"mtime",
",",
"'size'",
"=>",
"asset",
".",
"bytesize",
",",
"'digest'",
"=>",
"asset",
".",
"hexdigest",
",",
"# Deprecated: Remove beta integrity attribute in next release.",
"# Callers should DigestUtils.hexdigest_integrity_uri to compute the",
"# digest themselves.",
"'integrity'",
"=>",
"DigestUtils",
".",
"hexdigest_integrity_uri",
"(",
"asset",
".",
"hexdigest",
")",
"}",
"assets",
"[",
"asset",
".",
"logical_path",
"]",
"=",
"asset",
".",
"digest_path",
"filenames",
"<<",
"asset",
".",
"filename",
"promise",
"=",
"nil",
"exporters_for_asset",
"(",
"asset",
")",
"do",
"|",
"exporter",
"|",
"next",
"if",
"exporter",
".",
"skip?",
"(",
"logger",
")",
"if",
"promise",
".",
"nil?",
"promise",
"=",
"Concurrent",
"::",
"Promise",
".",
"new",
"(",
"executor",
":",
"executor",
")",
"{",
"exporter",
".",
"call",
"}",
"concurrent_exporters",
"<<",
"promise",
".",
"execute",
"else",
"concurrent_exporters",
"<<",
"promise",
".",
"then",
"{",
"exporter",
".",
"call",
"}",
"end",
"end",
"end",
"# make sure all exporters have finished before returning the main thread",
"concurrent_exporters",
".",
"each",
"(",
":wait!",
")",
"save",
"filenames",
"end"
] |
Compile asset to directory. The asset is written to a
fingerprinted filename like
`application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js`. An entry is
also inserted into the manifest file.
compile("application.js")
|
[
"Compile",
"asset",
"to",
"directory",
".",
"The",
"asset",
"is",
"written",
"to",
"a",
"fingerprinted",
"filename",
"like",
"application",
"-",
"2e8e9a7c6b0aafa0c9bdeec90ea30213",
".",
"js",
".",
"An",
"entry",
"is",
"also",
"inserted",
"into",
"the",
"manifest",
"file",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/manifest.rb#L160-L208
|
12,636
|
rails/sprockets
|
lib/sprockets/manifest.rb
|
Sprockets.Manifest.remove
|
def remove(filename)
path = File.join(dir, filename)
gzip = "#{path}.gz"
logical_path = files[filename]['logical_path']
if assets[logical_path] == filename
assets.delete(logical_path)
end
files.delete(filename)
FileUtils.rm(path) if File.exist?(path)
FileUtils.rm(gzip) if File.exist?(gzip)
save
logger.info "Removed #{filename}"
nil
end
|
ruby
|
def remove(filename)
path = File.join(dir, filename)
gzip = "#{path}.gz"
logical_path = files[filename]['logical_path']
if assets[logical_path] == filename
assets.delete(logical_path)
end
files.delete(filename)
FileUtils.rm(path) if File.exist?(path)
FileUtils.rm(gzip) if File.exist?(gzip)
save
logger.info "Removed #{filename}"
nil
end
|
[
"def",
"remove",
"(",
"filename",
")",
"path",
"=",
"File",
".",
"join",
"(",
"dir",
",",
"filename",
")",
"gzip",
"=",
"\"#{path}.gz\"",
"logical_path",
"=",
"files",
"[",
"filename",
"]",
"[",
"'logical_path'",
"]",
"if",
"assets",
"[",
"logical_path",
"]",
"==",
"filename",
"assets",
".",
"delete",
"(",
"logical_path",
")",
"end",
"files",
".",
"delete",
"(",
"filename",
")",
"FileUtils",
".",
"rm",
"(",
"path",
")",
"if",
"File",
".",
"exist?",
"(",
"path",
")",
"FileUtils",
".",
"rm",
"(",
"gzip",
")",
"if",
"File",
".",
"exist?",
"(",
"gzip",
")",
"save",
"logger",
".",
"info",
"\"Removed #{filename}\"",
"nil",
"end"
] |
Removes file from directory and from manifest. `filename` must
be the name with any directory path.
manifest.remove("application-2e8e9a7c6b0aafa0c9bdeec90ea30213.js")
|
[
"Removes",
"file",
"from",
"directory",
"and",
"from",
"manifest",
".",
"filename",
"must",
"be",
"the",
"name",
"with",
"any",
"directory",
"path",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/manifest.rb#L215-L233
|
12,637
|
rails/sprockets
|
lib/sprockets/manifest.rb
|
Sprockets.Manifest.clean
|
def clean(count = 2, age = 3600)
asset_versions = files.group_by { |_, attrs| attrs['logical_path'] }
asset_versions.each do |logical_path, versions|
current = assets[logical_path]
versions.reject { |path, _|
path == current
}.sort_by { |_, attrs|
# Sort by timestamp
Time.parse(attrs['mtime'])
}.reverse.each_with_index.drop_while { |(_, attrs), index|
_age = [0, Time.now - Time.parse(attrs['mtime'])].max
# Keep if under age or within the count limit
_age < age || index < count
}.each { |(path, _), _|
# Remove old assets
remove(path)
}
end
end
|
ruby
|
def clean(count = 2, age = 3600)
asset_versions = files.group_by { |_, attrs| attrs['logical_path'] }
asset_versions.each do |logical_path, versions|
current = assets[logical_path]
versions.reject { |path, _|
path == current
}.sort_by { |_, attrs|
# Sort by timestamp
Time.parse(attrs['mtime'])
}.reverse.each_with_index.drop_while { |(_, attrs), index|
_age = [0, Time.now - Time.parse(attrs['mtime'])].max
# Keep if under age or within the count limit
_age < age || index < count
}.each { |(path, _), _|
# Remove old assets
remove(path)
}
end
end
|
[
"def",
"clean",
"(",
"count",
"=",
"2",
",",
"age",
"=",
"3600",
")",
"asset_versions",
"=",
"files",
".",
"group_by",
"{",
"|",
"_",
",",
"attrs",
"|",
"attrs",
"[",
"'logical_path'",
"]",
"}",
"asset_versions",
".",
"each",
"do",
"|",
"logical_path",
",",
"versions",
"|",
"current",
"=",
"assets",
"[",
"logical_path",
"]",
"versions",
".",
"reject",
"{",
"|",
"path",
",",
"_",
"|",
"path",
"==",
"current",
"}",
".",
"sort_by",
"{",
"|",
"_",
",",
"attrs",
"|",
"# Sort by timestamp",
"Time",
".",
"parse",
"(",
"attrs",
"[",
"'mtime'",
"]",
")",
"}",
".",
"reverse",
".",
"each_with_index",
".",
"drop_while",
"{",
"|",
"(",
"_",
",",
"attrs",
")",
",",
"index",
"|",
"_age",
"=",
"[",
"0",
",",
"Time",
".",
"now",
"-",
"Time",
".",
"parse",
"(",
"attrs",
"[",
"'mtime'",
"]",
")",
"]",
".",
"max",
"# Keep if under age or within the count limit",
"_age",
"<",
"age",
"||",
"index",
"<",
"count",
"}",
".",
"each",
"{",
"|",
"(",
"path",
",",
"_",
")",
",",
"_",
"|",
"# Remove old assets",
"remove",
"(",
"path",
")",
"}",
"end",
"end"
] |
Cleanup old assets in the compile directory. By default it will
keep the latest version, 2 backups and any created within the past hour.
Examples
To force only 1 backup to be kept, set count=1 and age=0.
To only keep files created within the last 10 minutes, set count=0 and
age=600.
|
[
"Cleanup",
"old",
"assets",
"in",
"the",
"compile",
"directory",
".",
"By",
"default",
"it",
"will",
"keep",
"the",
"latest",
"version",
"2",
"backups",
"and",
"any",
"created",
"within",
"the",
"past",
"hour",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/manifest.rb#L245-L265
|
12,638
|
rails/sprockets
|
lib/sprockets/manifest.rb
|
Sprockets.Manifest.save
|
def save
data = json_encode(@data)
FileUtils.mkdir_p File.dirname(@filename)
PathUtils.atomic_write(@filename) do |f|
f.write(data)
end
end
|
ruby
|
def save
data = json_encode(@data)
FileUtils.mkdir_p File.dirname(@filename)
PathUtils.atomic_write(@filename) do |f|
f.write(data)
end
end
|
[
"def",
"save",
"data",
"=",
"json_encode",
"(",
"@data",
")",
"FileUtils",
".",
"mkdir_p",
"File",
".",
"dirname",
"(",
"@filename",
")",
"PathUtils",
".",
"atomic_write",
"(",
"@filename",
")",
"do",
"|",
"f",
"|",
"f",
".",
"write",
"(",
"data",
")",
"end",
"end"
] |
Persist manfiest back to FS
|
[
"Persist",
"manfiest",
"back",
"to",
"FS"
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/manifest.rb#L277-L283
|
12,639
|
rails/sprockets
|
lib/sprockets/manifest.rb
|
Sprockets.Manifest.exporters_for_asset
|
def exporters_for_asset(asset)
exporters = [Exporters::FileExporter]
environment.exporters.each do |mime_type, exporter_list|
next unless asset.content_type
next unless environment.match_mime_type? asset.content_type, mime_type
exporter_list.each do |exporter|
exporters << exporter
end
end
exporters.uniq!
exporters.each do |exporter|
yield exporter.new(asset: asset, environment: environment, directory: dir)
end
end
|
ruby
|
def exporters_for_asset(asset)
exporters = [Exporters::FileExporter]
environment.exporters.each do |mime_type, exporter_list|
next unless asset.content_type
next unless environment.match_mime_type? asset.content_type, mime_type
exporter_list.each do |exporter|
exporters << exporter
end
end
exporters.uniq!
exporters.each do |exporter|
yield exporter.new(asset: asset, environment: environment, directory: dir)
end
end
|
[
"def",
"exporters_for_asset",
"(",
"asset",
")",
"exporters",
"=",
"[",
"Exporters",
"::",
"FileExporter",
"]",
"environment",
".",
"exporters",
".",
"each",
"do",
"|",
"mime_type",
",",
"exporter_list",
"|",
"next",
"unless",
"asset",
".",
"content_type",
"next",
"unless",
"environment",
".",
"match_mime_type?",
"asset",
".",
"content_type",
",",
"mime_type",
"exporter_list",
".",
"each",
"do",
"|",
"exporter",
"|",
"exporters",
"<<",
"exporter",
"end",
"end",
"exporters",
".",
"uniq!",
"exporters",
".",
"each",
"do",
"|",
"exporter",
"|",
"yield",
"exporter",
".",
"new",
"(",
"asset",
":",
"asset",
",",
"environment",
":",
"environment",
",",
"directory",
":",
"dir",
")",
"end",
"end"
] |
Given an asset, finds all exporters that
match its mime-type.
Will yield each expoter to the passed in block.
array = []
puts asset.content_type # => "application/javascript"
exporters_for_asset(asset) do |exporter|
array << exporter
end
# puts array => [Exporters::FileExporter, Exporters::ZlibExporter]
|
[
"Given",
"an",
"asset",
"finds",
"all",
"exporters",
"that",
"match",
"its",
"mime",
"-",
"type",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/manifest.rb#L298-L314
|
12,640
|
rails/sprockets
|
lib/sprockets/server.rb
|
Sprockets.Server.call
|
def call(env)
start_time = Time.now.to_f
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
unless ALLOWED_REQUEST_METHODS.include? env['REQUEST_METHOD']
return method_not_allowed_response
end
msg = "Served asset #{env['PATH_INFO']} -"
# Extract the path from everything after the leading slash
path = Rack::Utils.unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
unless path.valid_encoding?
return bad_request_response(env)
end
# Strip fingerprint
if fingerprint = path_fingerprint(path)
path = path.sub("-#{fingerprint}", '')
end
# URLs containing a `".."` are rejected for security reasons.
if forbidden_request?(path)
return forbidden_response(env)
end
if fingerprint
if_match = fingerprint
elsif env['HTTP_IF_MATCH']
if_match = env['HTTP_IF_MATCH'][/"(\w+)"$/, 1]
end
if env['HTTP_IF_NONE_MATCH']
if_none_match = env['HTTP_IF_NONE_MATCH'][/"(\w+)"$/, 1]
end
# Look up the asset.
asset = find_asset(path)
if asset.nil?
status = :not_found
elsif fingerprint && asset.etag != fingerprint
status = :not_found
elsif if_match && asset.etag != if_match
status = :precondition_failed
elsif if_none_match && asset.etag == if_none_match
status = :not_modified
else
status = :ok
end
case status
when :ok
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
ok_response(asset, env)
when :not_modified
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
not_modified_response(env, if_none_match)
when :not_found
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
not_found_response(env)
when :precondition_failed
logger.info "#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)"
precondition_failed_response(env)
end
rescue Exception => e
logger.error "Error compiling asset #{path}:"
logger.error "#{e.class.name}: #{e.message}"
case File.extname(path)
when ".js"
# Re-throw JavaScript asset exceptions to the browser
logger.info "#{msg} 500 Internal Server Error\n\n"
return javascript_exception_response(e)
when ".css"
# Display CSS asset exceptions in the browser
logger.info "#{msg} 500 Internal Server Error\n\n"
return css_exception_response(e)
else
raise
end
end
|
ruby
|
def call(env)
start_time = Time.now.to_f
time_elapsed = lambda { ((Time.now.to_f - start_time) * 1000).to_i }
unless ALLOWED_REQUEST_METHODS.include? env['REQUEST_METHOD']
return method_not_allowed_response
end
msg = "Served asset #{env['PATH_INFO']} -"
# Extract the path from everything after the leading slash
path = Rack::Utils.unescape(env['PATH_INFO'].to_s.sub(/^\//, ''))
unless path.valid_encoding?
return bad_request_response(env)
end
# Strip fingerprint
if fingerprint = path_fingerprint(path)
path = path.sub("-#{fingerprint}", '')
end
# URLs containing a `".."` are rejected for security reasons.
if forbidden_request?(path)
return forbidden_response(env)
end
if fingerprint
if_match = fingerprint
elsif env['HTTP_IF_MATCH']
if_match = env['HTTP_IF_MATCH'][/"(\w+)"$/, 1]
end
if env['HTTP_IF_NONE_MATCH']
if_none_match = env['HTTP_IF_NONE_MATCH'][/"(\w+)"$/, 1]
end
# Look up the asset.
asset = find_asset(path)
if asset.nil?
status = :not_found
elsif fingerprint && asset.etag != fingerprint
status = :not_found
elsif if_match && asset.etag != if_match
status = :precondition_failed
elsif if_none_match && asset.etag == if_none_match
status = :not_modified
else
status = :ok
end
case status
when :ok
logger.info "#{msg} 200 OK (#{time_elapsed.call}ms)"
ok_response(asset, env)
when :not_modified
logger.info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)"
not_modified_response(env, if_none_match)
when :not_found
logger.info "#{msg} 404 Not Found (#{time_elapsed.call}ms)"
not_found_response(env)
when :precondition_failed
logger.info "#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)"
precondition_failed_response(env)
end
rescue Exception => e
logger.error "Error compiling asset #{path}:"
logger.error "#{e.class.name}: #{e.message}"
case File.extname(path)
when ".js"
# Re-throw JavaScript asset exceptions to the browser
logger.info "#{msg} 500 Internal Server Error\n\n"
return javascript_exception_response(e)
when ".css"
# Display CSS asset exceptions in the browser
logger.info "#{msg} 500 Internal Server Error\n\n"
return css_exception_response(e)
else
raise
end
end
|
[
"def",
"call",
"(",
"env",
")",
"start_time",
"=",
"Time",
".",
"now",
".",
"to_f",
"time_elapsed",
"=",
"lambda",
"{",
"(",
"(",
"Time",
".",
"now",
".",
"to_f",
"-",
"start_time",
")",
"*",
"1000",
")",
".",
"to_i",
"}",
"unless",
"ALLOWED_REQUEST_METHODS",
".",
"include?",
"env",
"[",
"'REQUEST_METHOD'",
"]",
"return",
"method_not_allowed_response",
"end",
"msg",
"=",
"\"Served asset #{env['PATH_INFO']} -\"",
"# Extract the path from everything after the leading slash",
"path",
"=",
"Rack",
"::",
"Utils",
".",
"unescape",
"(",
"env",
"[",
"'PATH_INFO'",
"]",
".",
"to_s",
".",
"sub",
"(",
"/",
"\\/",
"/",
",",
"''",
")",
")",
"unless",
"path",
".",
"valid_encoding?",
"return",
"bad_request_response",
"(",
"env",
")",
"end",
"# Strip fingerprint",
"if",
"fingerprint",
"=",
"path_fingerprint",
"(",
"path",
")",
"path",
"=",
"path",
".",
"sub",
"(",
"\"-#{fingerprint}\"",
",",
"''",
")",
"end",
"# URLs containing a `\"..\"` are rejected for security reasons.",
"if",
"forbidden_request?",
"(",
"path",
")",
"return",
"forbidden_response",
"(",
"env",
")",
"end",
"if",
"fingerprint",
"if_match",
"=",
"fingerprint",
"elsif",
"env",
"[",
"'HTTP_IF_MATCH'",
"]",
"if_match",
"=",
"env",
"[",
"'HTTP_IF_MATCH'",
"]",
"[",
"/",
"\\w",
"/",
",",
"1",
"]",
"end",
"if",
"env",
"[",
"'HTTP_IF_NONE_MATCH'",
"]",
"if_none_match",
"=",
"env",
"[",
"'HTTP_IF_NONE_MATCH'",
"]",
"[",
"/",
"\\w",
"/",
",",
"1",
"]",
"end",
"# Look up the asset.",
"asset",
"=",
"find_asset",
"(",
"path",
")",
"if",
"asset",
".",
"nil?",
"status",
"=",
":not_found",
"elsif",
"fingerprint",
"&&",
"asset",
".",
"etag",
"!=",
"fingerprint",
"status",
"=",
":not_found",
"elsif",
"if_match",
"&&",
"asset",
".",
"etag",
"!=",
"if_match",
"status",
"=",
":precondition_failed",
"elsif",
"if_none_match",
"&&",
"asset",
".",
"etag",
"==",
"if_none_match",
"status",
"=",
":not_modified",
"else",
"status",
"=",
":ok",
"end",
"case",
"status",
"when",
":ok",
"logger",
".",
"info",
"\"#{msg} 200 OK (#{time_elapsed.call}ms)\"",
"ok_response",
"(",
"asset",
",",
"env",
")",
"when",
":not_modified",
"logger",
".",
"info",
"\"#{msg} 304 Not Modified (#{time_elapsed.call}ms)\"",
"not_modified_response",
"(",
"env",
",",
"if_none_match",
")",
"when",
":not_found",
"logger",
".",
"info",
"\"#{msg} 404 Not Found (#{time_elapsed.call}ms)\"",
"not_found_response",
"(",
"env",
")",
"when",
":precondition_failed",
"logger",
".",
"info",
"\"#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)\"",
"precondition_failed_response",
"(",
"env",
")",
"end",
"rescue",
"Exception",
"=>",
"e",
"logger",
".",
"error",
"\"Error compiling asset #{path}:\"",
"logger",
".",
"error",
"\"#{e.class.name}: #{e.message}\"",
"case",
"File",
".",
"extname",
"(",
"path",
")",
"when",
"\".js\"",
"# Re-throw JavaScript asset exceptions to the browser",
"logger",
".",
"info",
"\"#{msg} 500 Internal Server Error\\n\\n\"",
"return",
"javascript_exception_response",
"(",
"e",
")",
"when",
"\".css\"",
"# Display CSS asset exceptions in the browser",
"logger",
".",
"info",
"\"#{msg} 500 Internal Server Error\\n\\n\"",
"return",
"css_exception_response",
"(",
"e",
")",
"else",
"raise",
"end",
"end"
] |
`call` implements the Rack 1.x specification which accepts an
`env` Hash and returns a three item tuple with the status code,
headers, and body.
Mapping your environment at a url prefix will serve all assets
in the path.
map "/assets" do
run Sprockets::Environment.new
end
A request for `"/assets/foo/bar.js"` will search your
environment for `"foo/bar.js"`.
|
[
"call",
"implements",
"the",
"Rack",
"1",
".",
"x",
"specification",
"which",
"accepts",
"an",
"env",
"Hash",
"and",
"returns",
"a",
"three",
"item",
"tuple",
"with",
"the",
"status",
"code",
"headers",
"and",
"body",
"."
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/server.rb#L27-L109
|
12,641
|
rails/sprockets
|
lib/sprockets/server.rb
|
Sprockets.Server.ok_response
|
def ok_response(asset, env)
if head_request?(env)
[ 200, headers(env, asset, 0), [] ]
else
[ 200, headers(env, asset, asset.length), asset ]
end
end
|
ruby
|
def ok_response(asset, env)
if head_request?(env)
[ 200, headers(env, asset, 0), [] ]
else
[ 200, headers(env, asset, asset.length), asset ]
end
end
|
[
"def",
"ok_response",
"(",
"asset",
",",
"env",
")",
"if",
"head_request?",
"(",
"env",
")",
"[",
"200",
",",
"headers",
"(",
"env",
",",
"asset",
",",
"0",
")",
",",
"[",
"]",
"]",
"else",
"[",
"200",
",",
"headers",
"(",
"env",
",",
"asset",
",",
"asset",
".",
"length",
")",
",",
"asset",
"]",
"end",
"end"
] |
Returns a 200 OK response tuple
|
[
"Returns",
"a",
"200",
"OK",
"response",
"tuple"
] |
9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd
|
https://github.com/rails/sprockets/blob/9e3f0d8e98c44f57e67bc138db87bb8469bf5ddd/lib/sprockets/server.rb#L125-L131
|
12,642
|
refinery/refinerycms
|
images/app/models/refinery/image.rb
|
Refinery.Image.thumbnail
|
def thumbnail(options = {})
options = { geometry: nil, strip: false }.merge(options)
geometry = convert_to_geometry(options[:geometry])
thumbnail = image
thumbnail = thumbnail.thumb(geometry) if geometry
thumbnail = thumbnail.strip if options[:strip]
thumbnail
end
|
ruby
|
def thumbnail(options = {})
options = { geometry: nil, strip: false }.merge(options)
geometry = convert_to_geometry(options[:geometry])
thumbnail = image
thumbnail = thumbnail.thumb(geometry) if geometry
thumbnail = thumbnail.strip if options[:strip]
thumbnail
end
|
[
"def",
"thumbnail",
"(",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"{",
"geometry",
":",
"nil",
",",
"strip",
":",
"false",
"}",
".",
"merge",
"(",
"options",
")",
"geometry",
"=",
"convert_to_geometry",
"(",
"options",
"[",
":geometry",
"]",
")",
"thumbnail",
"=",
"image",
"thumbnail",
"=",
"thumbnail",
".",
"thumb",
"(",
"geometry",
")",
"if",
"geometry",
"thumbnail",
"=",
"thumbnail",
".",
"strip",
"if",
"options",
"[",
":strip",
"]",
"thumbnail",
"end"
] |
Get a thumbnail job object given a geometry and whether to strip image profiles and comments.
|
[
"Get",
"a",
"thumbnail",
"job",
"object",
"given",
"a",
"geometry",
"and",
"whether",
"to",
"strip",
"image",
"profiles",
"and",
"comments",
"."
] |
67f117f937c5264ec0aeabe8e7eac1d562c5bc7b
|
https://github.com/refinery/refinerycms/blob/67f117f937c5264ec0aeabe8e7eac1d562c5bc7b/images/app/models/refinery/image.rb#L43-L50
|
12,643
|
refinery/refinerycms
|
images/app/models/refinery/image.rb
|
Refinery.Image.thumbnail_dimensions
|
def thumbnail_dimensions(geometry)
dimensions = ThumbnailDimensions.new(geometry, image.width, image.height)
{ width: dimensions.width, height: dimensions.height }
end
|
ruby
|
def thumbnail_dimensions(geometry)
dimensions = ThumbnailDimensions.new(geometry, image.width, image.height)
{ width: dimensions.width, height: dimensions.height }
end
|
[
"def",
"thumbnail_dimensions",
"(",
"geometry",
")",
"dimensions",
"=",
"ThumbnailDimensions",
".",
"new",
"(",
"geometry",
",",
"image",
".",
"width",
",",
"image",
".",
"height",
")",
"{",
"width",
":",
"dimensions",
".",
"width",
",",
"height",
":",
"dimensions",
".",
"height",
"}",
"end"
] |
Intelligently works out dimensions for a thumbnail of this image based on the Dragonfly geometry string.
|
[
"Intelligently",
"works",
"out",
"dimensions",
"for",
"a",
"thumbnail",
"of",
"this",
"image",
"based",
"on",
"the",
"Dragonfly",
"geometry",
"string",
"."
] |
67f117f937c5264ec0aeabe8e7eac1d562c5bc7b
|
https://github.com/refinery/refinerycms/blob/67f117f937c5264ec0aeabe8e7eac1d562c5bc7b/images/app/models/refinery/image.rb#L53-L56
|
12,644
|
refinery/refinerycms
|
pages/app/models/refinery/page.rb
|
Refinery.Page.reposition_parts!
|
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_columns position: index
end
end
|
ruby
|
def reposition_parts!
reload.parts.each_with_index do |part, index|
part.update_columns position: index
end
end
|
[
"def",
"reposition_parts!",
"reload",
".",
"parts",
".",
"each_with_index",
"do",
"|",
"part",
",",
"index",
"|",
"part",
".",
"update_columns",
"position",
":",
"index",
"end",
"end"
] |
Repositions the child page_parts that belong to this page.
This ensures that they are in the correct 0,1,2,3,4... etc order.
|
[
"Repositions",
"the",
"child",
"page_parts",
"that",
"belong",
"to",
"this",
"page",
".",
"This",
"ensures",
"that",
"they",
"are",
"in",
"the",
"correct",
"0",
"1",
"2",
"3",
"4",
"...",
"etc",
"order",
"."
] |
67f117f937c5264ec0aeabe8e7eac1d562c5bc7b
|
https://github.com/refinery/refinerycms/blob/67f117f937c5264ec0aeabe8e7eac1d562c5bc7b/pages/app/models/refinery/page.rb#L190-L194
|
12,645
|
refinery/refinerycms
|
pages/app/models/refinery/page.rb
|
Refinery.Page.path
|
def path(path_separator: ' - ', ancestors_first: true)
return title if root?
chain = ancestors_first ? self_and_ancestors : self_and_ancestors.reverse
chain.map(&:title).join(path_separator)
end
|
ruby
|
def path(path_separator: ' - ', ancestors_first: true)
return title if root?
chain = ancestors_first ? self_and_ancestors : self_and_ancestors.reverse
chain.map(&:title).join(path_separator)
end
|
[
"def",
"path",
"(",
"path_separator",
":",
"' - '",
",",
"ancestors_first",
":",
"true",
")",
"return",
"title",
"if",
"root?",
"chain",
"=",
"ancestors_first",
"?",
"self_and_ancestors",
":",
"self_and_ancestors",
".",
"reverse",
"chain",
".",
"map",
"(",
":title",
")",
".",
"join",
"(",
"path_separator",
")",
"end"
] |
Returns the full path to this page.
This automatically prints out this page title and all parent page titles.
The result is joined by the path_separator argument.
|
[
"Returns",
"the",
"full",
"path",
"to",
"this",
"page",
".",
"This",
"automatically",
"prints",
"out",
"this",
"page",
"title",
"and",
"all",
"parent",
"page",
"titles",
".",
"The",
"result",
"is",
"joined",
"by",
"the",
"path_separator",
"argument",
"."
] |
67f117f937c5264ec0aeabe8e7eac1d562c5bc7b
|
https://github.com/refinery/refinerycms/blob/67f117f937c5264ec0aeabe8e7eac1d562c5bc7b/pages/app/models/refinery/page.rb#L216-L221
|
12,646
|
refinery/refinerycms
|
core/app/helpers/refinery/site_bar_helper.rb
|
Refinery.SiteBarHelper.site_bar_switch_link
|
def site_bar_switch_link
link_to_if(admin?, t('.switch_to_your_website', site_bar_translate_locale_args),
refinery.root_path(site_bar_translate_locale_args),
'data-turbolinks' => false) do
link_to t('.switch_to_your_website_editor', site_bar_translate_locale_args),
Refinery::Core.backend_path, 'data-turbolinks' => false
end
end
|
ruby
|
def site_bar_switch_link
link_to_if(admin?, t('.switch_to_your_website', site_bar_translate_locale_args),
refinery.root_path(site_bar_translate_locale_args),
'data-turbolinks' => false) do
link_to t('.switch_to_your_website_editor', site_bar_translate_locale_args),
Refinery::Core.backend_path, 'data-turbolinks' => false
end
end
|
[
"def",
"site_bar_switch_link",
"link_to_if",
"(",
"admin?",
",",
"t",
"(",
"'.switch_to_your_website'",
",",
"site_bar_translate_locale_args",
")",
",",
"refinery",
".",
"root_path",
"(",
"site_bar_translate_locale_args",
")",
",",
"'data-turbolinks'",
"=>",
"false",
")",
"do",
"link_to",
"t",
"(",
"'.switch_to_your_website_editor'",
",",
"site_bar_translate_locale_args",
")",
",",
"Refinery",
"::",
"Core",
".",
"backend_path",
",",
"'data-turbolinks'",
"=>",
"false",
"end",
"end"
] |
Generates the link to determine where the site bar switch button returns to.
|
[
"Generates",
"the",
"link",
"to",
"determine",
"where",
"the",
"site",
"bar",
"switch",
"button",
"returns",
"to",
"."
] |
67f117f937c5264ec0aeabe8e7eac1d562c5bc7b
|
https://github.com/refinery/refinerycms/blob/67f117f937c5264ec0aeabe8e7eac1d562c5bc7b/core/app/helpers/refinery/site_bar_helper.rb#L5-L12
|
12,647
|
refinery/refinerycms
|
core/app/helpers/refinery/image_helper.rb
|
Refinery.ImageHelper.image_fu
|
def image_fu(image, geometry = nil, options = {})
return nil if image.blank?
thumbnail_args = options.slice(:strip)
thumbnail_args[:geometry] = geometry if geometry
image_tag_args = (image.thumbnail_dimensions(geometry) rescue {})
image_tag_args[:alt] = image.respond_to?(:title) ? image.title : image.image_name
image_tag(image.thumbnail(thumbnail_args).url, image_tag_args.merge(options))
end
|
ruby
|
def image_fu(image, geometry = nil, options = {})
return nil if image.blank?
thumbnail_args = options.slice(:strip)
thumbnail_args[:geometry] = geometry if geometry
image_tag_args = (image.thumbnail_dimensions(geometry) rescue {})
image_tag_args[:alt] = image.respond_to?(:title) ? image.title : image.image_name
image_tag(image.thumbnail(thumbnail_args).url, image_tag_args.merge(options))
end
|
[
"def",
"image_fu",
"(",
"image",
",",
"geometry",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
")",
"return",
"nil",
"if",
"image",
".",
"blank?",
"thumbnail_args",
"=",
"options",
".",
"slice",
"(",
":strip",
")",
"thumbnail_args",
"[",
":geometry",
"]",
"=",
"geometry",
"if",
"geometry",
"image_tag_args",
"=",
"(",
"image",
".",
"thumbnail_dimensions",
"(",
"geometry",
")",
"rescue",
"{",
"}",
")",
"image_tag_args",
"[",
":alt",
"]",
"=",
"image",
".",
"respond_to?",
"(",
":title",
")",
"?",
"image",
".",
"title",
":",
"image",
".",
"image_name",
"image_tag",
"(",
"image",
".",
"thumbnail",
"(",
"thumbnail_args",
")",
".",
"url",
",",
"image_tag_args",
".",
"merge",
"(",
"options",
")",
")",
"end"
] |
image_fu is a helper for inserting an image that has been uploaded into a template.
Say for example that we had a @model.image (@model having a belongs_to :image relationship)
and we wanted to display a thumbnail cropped to 200x200 then we can use image_fu like this:
<%= image_fu @model.image, '200x200' %> or with no thumbnail: <%= image_fu @model.image %>
|
[
"image_fu",
"is",
"a",
"helper",
"for",
"inserting",
"an",
"image",
"that",
"has",
"been",
"uploaded",
"into",
"a",
"template",
".",
"Say",
"for",
"example",
"that",
"we",
"had",
"a"
] |
67f117f937c5264ec0aeabe8e7eac1d562c5bc7b
|
https://github.com/refinery/refinerycms/blob/67f117f937c5264ec0aeabe8e7eac1d562c5bc7b/core/app/helpers/refinery/image_helper.rb#L23-L33
|
12,648
|
drapergem/draper
|
lib/draper/factory.rb
|
Draper.Factory.decorate
|
def decorate(object, options = {})
return nil if object.nil?
Worker.new(decorator_class, object).call(options.reverse_merge(default_options))
end
|
ruby
|
def decorate(object, options = {})
return nil if object.nil?
Worker.new(decorator_class, object).call(options.reverse_merge(default_options))
end
|
[
"def",
"decorate",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"return",
"nil",
"if",
"object",
".",
"nil?",
"Worker",
".",
"new",
"(",
"decorator_class",
",",
"object",
")",
".",
"call",
"(",
"options",
".",
"reverse_merge",
"(",
"default_options",
")",
")",
"end"
] |
Creates a decorator factory.
@option options [Decorator, CollectionDecorator] :with (nil)
decorator class to use. If nil, it is inferred from the object
passed to {#decorate}.
@option options [Hash, #call] context
extra data to be stored in created decorators. If a proc is given, it
will be called each time {#decorate} is called and its return value
will be used as the context.
Decorates an object, inferring whether to create a singular or collection
decorator from the type of object passed.
@param [Object] object
object to decorate.
@option options [Hash] context
extra data to be stored in the decorator. Overrides any context passed
to the constructor.
@option options [Object, Array] context_args (nil)
argument(s) to be passed to the context proc.
@return [Decorator, CollectionDecorator] the decorated object.
|
[
"Creates",
"a",
"decorator",
"factory",
"."
] |
d44c86f1e560afc0cf0dad4ae09bfaa3f10a1759
|
https://github.com/drapergem/draper/blob/d44c86f1e560afc0cf0dad4ae09bfaa3f10a1759/lib/draper/factory.rb#L29-L32
|
12,649
|
drapergem/draper
|
lib/draper/query_methods.rb
|
Draper.QueryMethods.method_missing
|
def method_missing(method, *args, &block)
return super unless strategy.allowed? method
object.send(method, *args, &block).decorate
end
|
ruby
|
def method_missing(method, *args, &block)
return super unless strategy.allowed? method
object.send(method, *args, &block).decorate
end
|
[
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"super",
"unless",
"strategy",
".",
"allowed?",
"method",
"object",
".",
"send",
"(",
"method",
",",
"args",
",",
"block",
")",
".",
"decorate",
"end"
] |
Proxies missing query methods to the source class if the strategy allows.
|
[
"Proxies",
"missing",
"query",
"methods",
"to",
"the",
"source",
"class",
"if",
"the",
"strategy",
"allows",
"."
] |
d44c86f1e560afc0cf0dad4ae09bfaa3f10a1759
|
https://github.com/drapergem/draper/blob/d44c86f1e560afc0cf0dad4ae09bfaa3f10a1759/lib/draper/query_methods.rb#L6-L10
|
12,650
|
norman/friendly_id
|
lib/friendly_id/configuration.rb
|
FriendlyId.Configuration.use
|
def use(*modules)
modules.to_a.flatten.compact.map do |object|
mod = get_module(object)
mod.setup(@model_class) if mod.respond_to?(:setup)
@model_class.send(:include, mod) unless uses? object
end
end
|
ruby
|
def use(*modules)
modules.to_a.flatten.compact.map do |object|
mod = get_module(object)
mod.setup(@model_class) if mod.respond_to?(:setup)
@model_class.send(:include, mod) unless uses? object
end
end
|
[
"def",
"use",
"(",
"*",
"modules",
")",
"modules",
".",
"to_a",
".",
"flatten",
".",
"compact",
".",
"map",
"do",
"|",
"object",
"|",
"mod",
"=",
"get_module",
"(",
"object",
")",
"mod",
".",
"setup",
"(",
"@model_class",
")",
"if",
"mod",
".",
"respond_to?",
"(",
":setup",
")",
"@model_class",
".",
"send",
"(",
":include",
",",
"mod",
")",
"unless",
"uses?",
"object",
"end",
"end"
] |
Lets you specify the addon modules to use with FriendlyId.
This method is invoked by {FriendlyId::Base#friendly_id friendly_id} when
passing the `:use` option, or when using {FriendlyId::Base#friendly_id
friendly_id} with a block.
@example
class Book < ActiveRecord::Base
extend FriendlyId
friendly_id :name, :use => :slugged
end
@param [#to_s,Module] modules Arguments should be Modules, or symbols or
strings that correspond with the name of an addon to use with FriendlyId.
By default FriendlyId provides `:slugged`, `:history`, `:simple_i18n`,
and `:scoped`.
|
[
"Lets",
"you",
"specify",
"the",
"addon",
"modules",
"to",
"use",
"with",
"FriendlyId",
"."
] |
67422c04e1bfed4207b2a04826bc67ec0e231ce7
|
https://github.com/norman/friendly_id/blob/67422c04e1bfed4207b2a04826bc67ec0e231ce7/lib/friendly_id/configuration.rb#L52-L58
|
12,651
|
norman/friendly_id
|
lib/friendly_id/slugged.rb
|
FriendlyId.Slugged.normalize_friendly_id
|
def normalize_friendly_id(value)
value = value.to_s.parameterize
value = value[0...friendly_id_config.slug_limit] if friendly_id_config.slug_limit
value
end
|
ruby
|
def normalize_friendly_id(value)
value = value.to_s.parameterize
value = value[0...friendly_id_config.slug_limit] if friendly_id_config.slug_limit
value
end
|
[
"def",
"normalize_friendly_id",
"(",
"value",
")",
"value",
"=",
"value",
".",
"to_s",
".",
"parameterize",
"value",
"=",
"value",
"[",
"0",
"...",
"friendly_id_config",
".",
"slug_limit",
"]",
"if",
"friendly_id_config",
".",
"slug_limit",
"value",
"end"
] |
Process the given value to make it suitable for use as a slug.
This method is not intended to be invoked directly; FriendlyId uses it
internally to process strings into slugs.
However, if FriendlyId's default slug generation doesn't suit your needs,
you can override this method in your model class to control exactly how
slugs are generated.
### Example
class Person < ActiveRecord::Base
extend FriendlyId
friendly_id :name_and_location
def name_and_location
"#{name} from #{location}"
end
# Use default slug, but upper case and with underscores
def normalize_friendly_id(string)
super.upcase.gsub("-", "_")
end
end
bob = Person.create! :name => "Bob Smith", :location => "New York City"
bob.friendly_id #=> "BOB_SMITH_FROM_NEW_YORK_CITY"
### More Resources
You might want to look into Babosa[https://github.com/norman/babosa],
which is the slugging library used by FriendlyId prior to version 4, which
offers some specialized functionality missing from Active Support.
@param [#to_s] value The value used as the basis of the slug.
@return The candidate slug text, without a sequence.
|
[
"Process",
"the",
"given",
"value",
"to",
"make",
"it",
"suitable",
"for",
"use",
"as",
"a",
"slug",
"."
] |
67422c04e1bfed4207b2a04826bc67ec0e231ce7
|
https://github.com/norman/friendly_id/blob/67422c04e1bfed4207b2a04826bc67ec0e231ce7/lib/friendly_id/slugged.rb#L290-L294
|
12,652
|
norman/friendly_id
|
lib/friendly_id/base.rb
|
FriendlyId.Base.friendly_id
|
def friendly_id(base = nil, options = {}, &block)
yield friendly_id_config if block_given?
friendly_id_config.dependent = options.delete :dependent
friendly_id_config.use options.delete :use
friendly_id_config.send :set, base ? options.merge(:base => base) : options
include Model
end
|
ruby
|
def friendly_id(base = nil, options = {}, &block)
yield friendly_id_config if block_given?
friendly_id_config.dependent = options.delete :dependent
friendly_id_config.use options.delete :use
friendly_id_config.send :set, base ? options.merge(:base => base) : options
include Model
end
|
[
"def",
"friendly_id",
"(",
"base",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"yield",
"friendly_id_config",
"if",
"block_given?",
"friendly_id_config",
".",
"dependent",
"=",
"options",
".",
"delete",
":dependent",
"friendly_id_config",
".",
"use",
"options",
".",
"delete",
":use",
"friendly_id_config",
".",
"send",
":set",
",",
"base",
"?",
"options",
".",
"merge",
"(",
":base",
"=>",
"base",
")",
":",
"options",
"include",
"Model",
"end"
] |
Configure FriendlyId's behavior in a model.
class Post < ActiveRecord::Base
extend FriendlyId
friendly_id :title, :use => :slugged
end
When given the optional block, this method will yield the class's instance
of {FriendlyId::Configuration} to the block before evaluating other
arguments, so configuration values set in the block may be overwritten by
the arguments. This order was chosen to allow passing the same proc to
multiple models, while being able to override the values it sets. Here is
a contrived example:
$friendly_id_config_proc = Proc.new do |config|
config.base = :name
config.use :slugged
end
class Foo < ActiveRecord::Base
extend FriendlyId
friendly_id &$friendly_id_config_proc
end
class Bar < ActiveRecord::Base
extend FriendlyId
friendly_id :title, &$friendly_id_config_proc
end
However, it's usually better to use {FriendlyId.defaults} for this:
FriendlyId.defaults do |config|
config.base = :name
config.use :slugged
end
class Foo < ActiveRecord::Base
extend FriendlyId
end
class Bar < ActiveRecord::Base
extend FriendlyId
friendly_id :title
end
In general you should use the block syntax either because of your personal
aesthetic preference, or because you need to share some functionality
between multiple models that can't be well encapsulated by
{FriendlyId.defaults}.
### Order Method Calls in a Block vs Ordering Options
When calling this method without a block, you may set the hash options in
any order.
However, when using block-style invocation, be sure to call
FriendlyId::Configuration's {FriendlyId::Configuration#use use} method
*prior* to the associated configuration options, because it will include
modules into your class, and these modules in turn may add required
configuration options to the `@friendly_id_configuraton`'s class:
class Person < ActiveRecord::Base
friendly_id do |config|
# This will work
config.use :slugged
config.sequence_separator = ":"
end
end
class Person < ActiveRecord::Base
friendly_id do |config|
# This will fail
config.sequence_separator = ":"
config.use :slugged
end
end
### Including Your Own Modules
Because :use can accept a name or a Module, {FriendlyId.defaults defaults}
can be a convenient place to set up behavior common to all classes using
FriendlyId. You can include any module, or more conveniently, define one
on-the-fly. For example, let's say you want to make
[Babosa](http://github.com/norman/babosa) the default slugging library in
place of Active Support, and transliterate all slugs from Russian Cyrillic
to ASCII:
require "babosa"
FriendlyId.defaults do |config|
config.base = :name
config.use :slugged
config.use Module.new {
def normalize_friendly_id(text)
text.to_slug.normalize! :transliterations => [:russian, :latin]
end
}
end
@option options [Symbol,Module] :use The addon or name of an addon to use.
By default, FriendlyId provides {FriendlyId::Slugged :slugged},
{FriendlyId::History :history}, {FriendlyId::Reserved :reserved}, and
{FriendlyId::Scoped :scoped}, and {FriendlyId::SimpleI18n :simple_i18n}.
@option options [Array] :reserved_words Available when using `:reserved`,
which is loaded by default. Sets an array of words banned for use as
the basis of a friendly_id. By default this includes "edit" and "new".
@option options [Symbol] :scope Available when using `:scoped`.
Sets the relation or column used to scope generated friendly ids. This
option has no default value.
@option options [Symbol] :sequence_separator Available when using `:slugged`.
Configures the sequence of characters used to separate a slug from a
sequence. Defaults to `-`.
@option options [Symbol] :slug_column Available when using `:slugged`.
Configures the name of the column where FriendlyId will store the slug.
Defaults to `:slug`.
@option options [Integer] :slug_limit Available when using `:slugged`.
Configures the limit of the slug. This option has no default value.
@option options [Symbol] :slug_generator_class Available when using `:slugged`.
Sets the class used to generate unique slugs. You should not specify this
unless you're doing some extensive hacking on FriendlyId. Defaults to
{FriendlyId::SlugGenerator}.
@yield Provides access to the model class's friendly_id_config, which
allows an alternate configuration syntax, and conditional configuration
logic.
@option options [Symbol,Boolean] :dependent Available when using `:history`.
Sets the value used for the slugged association's dependent option. Use
`false` if you do not want to dependently destroy the associated slugged
record. Defaults to `:destroy`.
@option options [Symbol] :routes When set to anything other than :friendly,
ensures that all routes generated by default do *not* use the slug. This
allows `form_for` and `polymorphic_path` to continue to generate paths like
`/team/1` instead of `/team/number-one`. You can still generate paths
like the latter using: team_path(team.slug). When set to :friendly, or
omitted, the default friendly_id behavior is maintained.
@yieldparam config The model class's {FriendlyId::Configuration friendly_id_config}.
|
[
"Configure",
"FriendlyId",
"s",
"behavior",
"in",
"a",
"model",
"."
] |
67422c04e1bfed4207b2a04826bc67ec0e231ce7
|
https://github.com/norman/friendly_id/blob/67422c04e1bfed4207b2a04826bc67ec0e231ce7/lib/friendly_id/base.rb#L206-L212
|
12,653
|
norman/friendly_id
|
lib/friendly_id/finder_methods.rb
|
FriendlyId.FinderMethods.find
|
def find(*args)
id = args.first
return super if args.count != 1 || id.unfriendly_id?
first_by_friendly_id(id).tap {|result| return result unless result.nil?}
return super if potential_primary_key?(id)
raise_not_found_exception id
end
|
ruby
|
def find(*args)
id = args.first
return super if args.count != 1 || id.unfriendly_id?
first_by_friendly_id(id).tap {|result| return result unless result.nil?}
return super if potential_primary_key?(id)
raise_not_found_exception id
end
|
[
"def",
"find",
"(",
"*",
"args",
")",
"id",
"=",
"args",
".",
"first",
"return",
"super",
"if",
"args",
".",
"count",
"!=",
"1",
"||",
"id",
".",
"unfriendly_id?",
"first_by_friendly_id",
"(",
"id",
")",
".",
"tap",
"{",
"|",
"result",
"|",
"return",
"result",
"unless",
"result",
".",
"nil?",
"}",
"return",
"super",
"if",
"potential_primary_key?",
"(",
"id",
")",
"raise_not_found_exception",
"id",
"end"
] |
Finds a record using the given id.
If the id is "unfriendly", it will call the original find method.
If the id is a numeric string like '123' it will first look for a friendly
id matching '123' and then fall back to looking for a record with the
numeric id '123'.
Since FriendlyId 5.0, if the id is a nonnumeric string like '123-foo' it
will *only* search by friendly id and not fall back to the regular find
method.
If you want to search only by the friendly id, use {#find_by_friendly_id}.
@raise ActiveRecord::RecordNotFound
|
[
"Finds",
"a",
"record",
"using",
"the",
"given",
"id",
"."
] |
67422c04e1bfed4207b2a04826bc67ec0e231ce7
|
https://github.com/norman/friendly_id/blob/67422c04e1bfed4207b2a04826bc67ec0e231ce7/lib/friendly_id/finder_methods.rb#L18-L25
|
12,654
|
ruckus/quickbooks-ruby
|
lib/quickbooks/util/name_entity.rb
|
NameEntity.PermitAlterations.valid_for_deletion?
|
def valid_for_deletion?
return false if(id.nil? || sync_token.nil?)
id.to_i > 0 && !sync_token.to_s.empty? && sync_token.to_i >= 0
end
|
ruby
|
def valid_for_deletion?
return false if(id.nil? || sync_token.nil?)
id.to_i > 0 && !sync_token.to_s.empty? && sync_token.to_i >= 0
end
|
[
"def",
"valid_for_deletion?",
"return",
"false",
"if",
"(",
"id",
".",
"nil?",
"||",
"sync_token",
".",
"nil?",
")",
"id",
".",
"to_i",
">",
"0",
"&&",
"!",
"sync_token",
".",
"to_s",
".",
"empty?",
"&&",
"sync_token",
".",
"to_i",
">=",
"0",
"end"
] |
To delete an account Intuit requires we provide Id and SyncToken fields
|
[
"To",
"delete",
"an",
"account",
"Intuit",
"requires",
"we",
"provide",
"Id",
"and",
"SyncToken",
"fields"
] |
b3b742389c438351f0826013e128ba706f1ed41c
|
https://github.com/ruckus/quickbooks-ruby/blob/b3b742389c438351f0826013e128ba706f1ed41c/lib/quickbooks/util/name_entity.rb#L80-L83
|
12,655
|
typhoeus/typhoeus
|
lib/typhoeus/easy_factory.rb
|
Typhoeus.EasyFactory.get
|
def get
begin
easy.http_request(
request.base_url.to_s,
request.options.fetch(:method, :get),
sanitize(request.options)
)
rescue Ethon::Errors::InvalidOption => e
help = provide_help(e.message.match(/:\s(\w+)/)[1])
raise $!, "#{$!}#{help}", $!.backtrace
end
set_callback
easy
end
|
ruby
|
def get
begin
easy.http_request(
request.base_url.to_s,
request.options.fetch(:method, :get),
sanitize(request.options)
)
rescue Ethon::Errors::InvalidOption => e
help = provide_help(e.message.match(/:\s(\w+)/)[1])
raise $!, "#{$!}#{help}", $!.backtrace
end
set_callback
easy
end
|
[
"def",
"get",
"begin",
"easy",
".",
"http_request",
"(",
"request",
".",
"base_url",
".",
"to_s",
",",
"request",
".",
"options",
".",
"fetch",
"(",
":method",
",",
":get",
")",
",",
"sanitize",
"(",
"request",
".",
"options",
")",
")",
"rescue",
"Ethon",
"::",
"Errors",
"::",
"InvalidOption",
"=>",
"e",
"help",
"=",
"provide_help",
"(",
"e",
".",
"message",
".",
"match",
"(",
"/",
"\\s",
"\\w",
"/",
")",
"[",
"1",
"]",
")",
"raise",
"$!",
",",
"\"#{$!}#{help}\"",
",",
"$!",
".",
"backtrace",
"end",
"set_callback",
"easy",
"end"
] |
Fabricated easy.
@example Prepared easy.
easy_factory.get
@return [ Ethon::Easy ] The easy.
|
[
"Fabricated",
"easy",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/easy_factory.rb#L79-L92
|
12,656
|
typhoeus/typhoeus
|
lib/typhoeus/easy_factory.rb
|
Typhoeus.EasyFactory.set_callback
|
def set_callback
if request.streaming?
response = nil
easy.on_headers do |easy|
response = Response.new(Ethon::Easy::Mirror.from_easy(easy).options)
request.execute_headers_callbacks(response)
end
request.on_body.each do |callback|
easy.on_body do |chunk, easy|
callback.call(chunk, response)
end
end
else
easy.on_headers do |easy|
request.execute_headers_callbacks(Response.new(Ethon::Easy::Mirror.from_easy(easy).options))
end
end
request.on_progress.each do |callback|
easy.on_progress do |dltotal, dlnow, ultotal, ulnow, easy|
callback.call(dltotal, dlnow, ultotal, ulnow, response)
end
end
easy.on_complete do |easy|
request.finish(Response.new(easy.mirror.options))
Typhoeus::Pool.release(easy)
if hydra && !hydra.queued_requests.empty?
hydra.dequeue_many
end
end
end
|
ruby
|
def set_callback
if request.streaming?
response = nil
easy.on_headers do |easy|
response = Response.new(Ethon::Easy::Mirror.from_easy(easy).options)
request.execute_headers_callbacks(response)
end
request.on_body.each do |callback|
easy.on_body do |chunk, easy|
callback.call(chunk, response)
end
end
else
easy.on_headers do |easy|
request.execute_headers_callbacks(Response.new(Ethon::Easy::Mirror.from_easy(easy).options))
end
end
request.on_progress.each do |callback|
easy.on_progress do |dltotal, dlnow, ultotal, ulnow, easy|
callback.call(dltotal, dlnow, ultotal, ulnow, response)
end
end
easy.on_complete do |easy|
request.finish(Response.new(easy.mirror.options))
Typhoeus::Pool.release(easy)
if hydra && !hydra.queued_requests.empty?
hydra.dequeue_many
end
end
end
|
[
"def",
"set_callback",
"if",
"request",
".",
"streaming?",
"response",
"=",
"nil",
"easy",
".",
"on_headers",
"do",
"|",
"easy",
"|",
"response",
"=",
"Response",
".",
"new",
"(",
"Ethon",
"::",
"Easy",
"::",
"Mirror",
".",
"from_easy",
"(",
"easy",
")",
".",
"options",
")",
"request",
".",
"execute_headers_callbacks",
"(",
"response",
")",
"end",
"request",
".",
"on_body",
".",
"each",
"do",
"|",
"callback",
"|",
"easy",
".",
"on_body",
"do",
"|",
"chunk",
",",
"easy",
"|",
"callback",
".",
"call",
"(",
"chunk",
",",
"response",
")",
"end",
"end",
"else",
"easy",
".",
"on_headers",
"do",
"|",
"easy",
"|",
"request",
".",
"execute_headers_callbacks",
"(",
"Response",
".",
"new",
"(",
"Ethon",
"::",
"Easy",
"::",
"Mirror",
".",
"from_easy",
"(",
"easy",
")",
".",
"options",
")",
")",
"end",
"end",
"request",
".",
"on_progress",
".",
"each",
"do",
"|",
"callback",
"|",
"easy",
".",
"on_progress",
"do",
"|",
"dltotal",
",",
"dlnow",
",",
"ultotal",
",",
"ulnow",
",",
"easy",
"|",
"callback",
".",
"call",
"(",
"dltotal",
",",
"dlnow",
",",
"ultotal",
",",
"ulnow",
",",
"response",
")",
"end",
"end",
"easy",
".",
"on_complete",
"do",
"|",
"easy",
"|",
"request",
".",
"finish",
"(",
"Response",
".",
"new",
"(",
"easy",
".",
"mirror",
".",
"options",
")",
")",
"Typhoeus",
"::",
"Pool",
".",
"release",
"(",
"easy",
")",
"if",
"hydra",
"&&",
"!",
"hydra",
".",
"queued_requests",
".",
"empty?",
"hydra",
".",
"dequeue_many",
"end",
"end",
"end"
] |
Sets on_complete callback on easy in order to be able to
track progress.
@example Set callback.
easy_factory.set_callback
@return [ Ethon::Easy ] The easy.
|
[
"Sets",
"on_complete",
"callback",
"on",
"easy",
"in",
"order",
"to",
"be",
"able",
"to",
"track",
"progress",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/easy_factory.rb#L141-L170
|
12,657
|
typhoeus/typhoeus
|
lib/typhoeus/request.rb
|
Typhoeus.Request.url
|
def url
easy = EasyFactory.new(self).get
url = easy.url
Typhoeus::Pool.release(easy)
url
end
|
ruby
|
def url
easy = EasyFactory.new(self).get
url = easy.url
Typhoeus::Pool.release(easy)
url
end
|
[
"def",
"url",
"easy",
"=",
"EasyFactory",
".",
"new",
"(",
"self",
")",
".",
"get",
"url",
"=",
"easy",
".",
"url",
"Typhoeus",
"::",
"Pool",
".",
"release",
"(",
"easy",
")",
"url",
"end"
] |
Creates a new request.
@example Simplest request.
response = Typhoeus::Request.new("www.example.com").run
@example Request with url parameters.
response = Typhoeus::Request.new(
"www.example.com",
params: {a: 1}
).run
@example Request with a body.
response = Typhoeus::Request.new(
"www.example.com",
body: {b: 2}
).run
@example Request with parameters and body.
response = Typhoeus::Request.new(
"www.example.com",
params: {a: 1},
body: {b: 2}
).run
@example Create a request and allow follow redirections.
response = Typhoeus::Request.new(
"www.example.com",
followlocation: true
).run
@param [ String ] base_url The url to request.
@param [ options ] options The options.
@option options [ Hash ] :params Translated
into url parameters.
@option options [ Hash ] :body Translated
into HTTP POST request body.
@return [ Typhoeus::Request ] The request.
@note See {http://rubydoc.info/github/typhoeus/ethon/Ethon/Easy/Options Ethon::Easy::Options} for more options.
@see Typhoeus::Hydra
@see Typhoeus::Response
@see Typhoeus::Request::Actions
Return the url.
In contrast to base_url which returns the value you specified, url returns
the full url including the parameters.
@example Get the url.
request.url
@since 0.5.5
|
[
"Creates",
"a",
"new",
"request",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/request.rb#L129-L134
|
12,658
|
typhoeus/typhoeus
|
lib/typhoeus/request.rb
|
Typhoeus.Request.fuzzy_hash_eql?
|
def fuzzy_hash_eql?(left, right)
return true if (left == right)
(left.count == right.count) && left.inject(true) do |res, kvp|
res && (kvp[1] == right[kvp[0]])
end
end
|
ruby
|
def fuzzy_hash_eql?(left, right)
return true if (left == right)
(left.count == right.count) && left.inject(true) do |res, kvp|
res && (kvp[1] == right[kvp[0]])
end
end
|
[
"def",
"fuzzy_hash_eql?",
"(",
"left",
",",
"right",
")",
"return",
"true",
"if",
"(",
"left",
"==",
"right",
")",
"(",
"left",
".",
"count",
"==",
"right",
".",
"count",
")",
"&&",
"left",
".",
"inject",
"(",
"true",
")",
"do",
"|",
"res",
",",
"kvp",
"|",
"res",
"&&",
"(",
"kvp",
"[",
"1",
"]",
"==",
"right",
"[",
"kvp",
"[",
"0",
"]",
"]",
")",
"end",
"end"
] |
Checks if two hashes are equal or not, discarding
first-level hash order.
@param [ Hash ] left
@param [ Hash ] right hash to check for equality
@return [ Boolean ] Returns true if hashes have
same values for same keys and same length,
even if the keys are given in a different order.
|
[
"Checks",
"if",
"two",
"hashes",
"are",
"equal",
"or",
"not",
"discarding",
"first",
"-",
"level",
"hash",
"order",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/request.rb#L191-L197
|
12,659
|
typhoeus/typhoeus
|
lib/typhoeus/request.rb
|
Typhoeus.Request.set_defaults
|
def set_defaults
default_user_agent = Config.user_agent || Typhoeus::USER_AGENT
options[:headers] = {'User-Agent' => default_user_agent}.merge(options[:headers] || {})
options[:headers]['Expect'] ||= ''
options[:verbose] = Typhoeus::Config.verbose if options[:verbose].nil? && !Typhoeus::Config.verbose.nil?
options[:maxredirs] ||= 50
options[:proxy] = Typhoeus::Config.proxy unless options.has_key?(:proxy) || Typhoeus::Config.proxy.nil?
end
|
ruby
|
def set_defaults
default_user_agent = Config.user_agent || Typhoeus::USER_AGENT
options[:headers] = {'User-Agent' => default_user_agent}.merge(options[:headers] || {})
options[:headers]['Expect'] ||= ''
options[:verbose] = Typhoeus::Config.verbose if options[:verbose].nil? && !Typhoeus::Config.verbose.nil?
options[:maxredirs] ||= 50
options[:proxy] = Typhoeus::Config.proxy unless options.has_key?(:proxy) || Typhoeus::Config.proxy.nil?
end
|
[
"def",
"set_defaults",
"default_user_agent",
"=",
"Config",
".",
"user_agent",
"||",
"Typhoeus",
"::",
"USER_AGENT",
"options",
"[",
":headers",
"]",
"=",
"{",
"'User-Agent'",
"=>",
"default_user_agent",
"}",
".",
"merge",
"(",
"options",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
"options",
"[",
":headers",
"]",
"[",
"'Expect'",
"]",
"||=",
"''",
"options",
"[",
":verbose",
"]",
"=",
"Typhoeus",
"::",
"Config",
".",
"verbose",
"if",
"options",
"[",
":verbose",
"]",
".",
"nil?",
"&&",
"!",
"Typhoeus",
"::",
"Config",
".",
"verbose",
".",
"nil?",
"options",
"[",
":maxredirs",
"]",
"||=",
"50",
"options",
"[",
":proxy",
"]",
"=",
"Typhoeus",
"::",
"Config",
".",
"proxy",
"unless",
"options",
".",
"has_key?",
"(",
":proxy",
")",
"||",
"Typhoeus",
"::",
"Config",
".",
"proxy",
".",
"nil?",
"end"
] |
Sets default header and verbose when turned on.
|
[
"Sets",
"default",
"header",
"and",
"verbose",
"when",
"turned",
"on",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/request.rb#L211-L219
|
12,660
|
typhoeus/typhoeus
|
lib/typhoeus/expectation.rb
|
Typhoeus.Expectation.and_return
|
def and_return(response=nil, &block)
new_response = (response.nil? ? block : response)
responses.push(*new_response)
end
|
ruby
|
def and_return(response=nil, &block)
new_response = (response.nil? ? block : response)
responses.push(*new_response)
end
|
[
"def",
"and_return",
"(",
"response",
"=",
"nil",
",",
"&",
"block",
")",
"new_response",
"=",
"(",
"response",
".",
"nil?",
"?",
"block",
":",
"response",
")",
"responses",
".",
"push",
"(",
"new_response",
")",
"end"
] |
Specify what should be returned,
when this expectation is hit.
@example Add response.
expectation.and_return(response)
@return [ void ]
|
[
"Specify",
"what",
"should",
"be",
"returned",
"when",
"this",
"expectation",
"is",
"hit",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/expectation.rb#L138-L141
|
12,661
|
typhoeus/typhoeus
|
lib/typhoeus/expectation.rb
|
Typhoeus.Expectation.response
|
def response(request)
response = responses.fetch(@response_counter, responses.last)
if response.respond_to?(:call)
response = response.call(request)
end
@response_counter += 1
response.mock = @from || true
response
end
|
ruby
|
def response(request)
response = responses.fetch(@response_counter, responses.last)
if response.respond_to?(:call)
response = response.call(request)
end
@response_counter += 1
response.mock = @from || true
response
end
|
[
"def",
"response",
"(",
"request",
")",
"response",
"=",
"responses",
".",
"fetch",
"(",
"@response_counter",
",",
"responses",
".",
"last",
")",
"if",
"response",
".",
"respond_to?",
"(",
":call",
")",
"response",
"=",
"response",
".",
"call",
"(",
"request",
")",
"end",
"@response_counter",
"+=",
"1",
"response",
".",
"mock",
"=",
"@from",
"||",
"true",
"response",
"end"
] |
Return the response. When there are
multiple responses, they are returned one
by one.
@example Return response.
expectation.response
@return [ Response ] The response.
@api private
|
[
"Return",
"the",
"response",
".",
"When",
"there",
"are",
"multiple",
"responses",
"they",
"are",
"returned",
"one",
"by",
"one",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/expectation.rb#L180-L188
|
12,662
|
typhoeus/typhoeus
|
lib/typhoeus/expectation.rb
|
Typhoeus.Expectation.options_match?
|
def options_match?(request)
(options ? options.all?{ |k,v| request.original_options[k] == v || request.options[k] == v } : true)
end
|
ruby
|
def options_match?(request)
(options ? options.all?{ |k,v| request.original_options[k] == v || request.options[k] == v } : true)
end
|
[
"def",
"options_match?",
"(",
"request",
")",
"(",
"options",
"?",
"options",
".",
"all?",
"{",
"|",
"k",
",",
"v",
"|",
"request",
".",
"original_options",
"[",
"k",
"]",
"==",
"v",
"||",
"request",
".",
"options",
"[",
"k",
"]",
"==",
"v",
"}",
":",
"true",
")",
"end"
] |
Check whether the options matches the request options.
I checks options and original options.
|
[
"Check",
"whether",
"the",
"options",
"matches",
"the",
"request",
"options",
".",
"I",
"checks",
"options",
"and",
"original",
"options",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/expectation.rb#L194-L196
|
12,663
|
typhoeus/typhoeus
|
lib/typhoeus/expectation.rb
|
Typhoeus.Expectation.url_match?
|
def url_match?(request_url)
case base_url
when String
base_url == request_url
when Regexp
base_url === request_url
when nil
true
else
false
end
end
|
ruby
|
def url_match?(request_url)
case base_url
when String
base_url == request_url
when Regexp
base_url === request_url
when nil
true
else
false
end
end
|
[
"def",
"url_match?",
"(",
"request_url",
")",
"case",
"base_url",
"when",
"String",
"base_url",
"==",
"request_url",
"when",
"Regexp",
"base_url",
"===",
"request_url",
"when",
"nil",
"true",
"else",
"false",
"end",
"end"
] |
Check whether the base_url matches the request url.
The base_url can be a string, regex or nil. String and
regexp are checked, nil is always true, else false.
Nil serves as a placeholder in case you want to match
all urls.
|
[
"Check",
"whether",
"the",
"base_url",
"matches",
"the",
"request",
"url",
".",
"The",
"base_url",
"can",
"be",
"a",
"string",
"regex",
"or",
"nil",
".",
"String",
"and",
"regexp",
"are",
"checked",
"nil",
"is",
"always",
"true",
"else",
"false",
"."
] |
d072aaf6edcf46d54d6a6bce45286629bf4e5af6
|
https://github.com/typhoeus/typhoeus/blob/d072aaf6edcf46d54d6a6bce45286629bf4e5af6/lib/typhoeus/expectation.rb#L204-L215
|
12,664
|
wearefine/fae
|
app/helpers/fae/form_helper.rb
|
Fae.FormHelper.list_order
|
def list_order(f, attribute, options)
if is_association?(f, attribute) && !options[:collection]
begin
options[:collection] = to_class(attribute).for_fae_index
rescue NameError
raise "Fae::MissingCollection: `#{attribute}` isn't an orderable class, define your order using the `collection` option."
end
end
end
|
ruby
|
def list_order(f, attribute, options)
if is_association?(f, attribute) && !options[:collection]
begin
options[:collection] = to_class(attribute).for_fae_index
rescue NameError
raise "Fae::MissingCollection: `#{attribute}` isn't an orderable class, define your order using the `collection` option."
end
end
end
|
[
"def",
"list_order",
"(",
"f",
",",
"attribute",
",",
"options",
")",
"if",
"is_association?",
"(",
"f",
",",
"attribute",
")",
"&&",
"!",
"options",
"[",
":collection",
"]",
"begin",
"options",
"[",
":collection",
"]",
"=",
"to_class",
"(",
"attribute",
")",
".",
"for_fae_index",
"rescue",
"NameError",
"raise",
"\"Fae::MissingCollection: `#{attribute}` isn't an orderable class, define your order using the `collection` option.\"",
"end",
"end",
"end"
] |
sets collection to class.for_fae_index if not defined
|
[
"sets",
"collection",
"to",
"class",
".",
"for_fae_index",
"if",
"not",
"defined"
] |
645d6b66945aeff54e27af6a95c4f8a1f7a67d39
|
https://github.com/wearefine/fae/blob/645d6b66945aeff54e27af6a95c4f8a1f7a67d39/app/helpers/fae/form_helper.rb#L183-L191
|
12,665
|
wearefine/fae
|
app/helpers/fae/form_helper.rb
|
Fae.FormHelper.set_prompt
|
def set_prompt(f, attribute, options)
options[:prompt] = 'Select One' if is_association?(f, attribute) && f.object.class.reflect_on_association(attribute).macro == :belongs_to && options[:prompt].nil? && !options[:two_pane]
end
|
ruby
|
def set_prompt(f, attribute, options)
options[:prompt] = 'Select One' if is_association?(f, attribute) && f.object.class.reflect_on_association(attribute).macro == :belongs_to && options[:prompt].nil? && !options[:two_pane]
end
|
[
"def",
"set_prompt",
"(",
"f",
",",
"attribute",
",",
"options",
")",
"options",
"[",
":prompt",
"]",
"=",
"'Select One'",
"if",
"is_association?",
"(",
"f",
",",
"attribute",
")",
"&&",
"f",
".",
"object",
".",
"class",
".",
"reflect_on_association",
"(",
"attribute",
")",
".",
"macro",
"==",
":belongs_to",
"&&",
"options",
"[",
":prompt",
"]",
".",
"nil?",
"&&",
"!",
"options",
"[",
":two_pane",
"]",
"end"
] |
sets default prompt for pulldowns
|
[
"sets",
"default",
"prompt",
"for",
"pulldowns"
] |
645d6b66945aeff54e27af6a95c4f8a1f7a67d39
|
https://github.com/wearefine/fae/blob/645d6b66945aeff54e27af6a95c4f8a1f7a67d39/app/helpers/fae/form_helper.rb#L194-L196
|
12,666
|
wearefine/fae
|
app/helpers/fae/form_helper.rb
|
Fae.FormHelper.language_support
|
def language_support(f, attribute, options)
return if Fae.languages.blank?
attribute_array = attribute.to_s.split('_')
language_suffix = attribute_array.pop
return unless Fae.languages.has_key?(language_suffix.to_sym) || Fae.languages.has_key?(language_suffix)
label = attribute_array.push("(#{language_suffix})").join(' ').titleize
options[:label] = label unless options[:label].present?
if options[:wrapper_html].present?
options[:wrapper_html].deep_merge!({ data: { language: language_suffix } })
else
options[:wrapper_html] = { data: { language: language_suffix } }
end
end
|
ruby
|
def language_support(f, attribute, options)
return if Fae.languages.blank?
attribute_array = attribute.to_s.split('_')
language_suffix = attribute_array.pop
return unless Fae.languages.has_key?(language_suffix.to_sym) || Fae.languages.has_key?(language_suffix)
label = attribute_array.push("(#{language_suffix})").join(' ').titleize
options[:label] = label unless options[:label].present?
if options[:wrapper_html].present?
options[:wrapper_html].deep_merge!({ data: { language: language_suffix } })
else
options[:wrapper_html] = { data: { language: language_suffix } }
end
end
|
[
"def",
"language_support",
"(",
"f",
",",
"attribute",
",",
"options",
")",
"return",
"if",
"Fae",
".",
"languages",
".",
"blank?",
"attribute_array",
"=",
"attribute",
".",
"to_s",
".",
"split",
"(",
"'_'",
")",
"language_suffix",
"=",
"attribute_array",
".",
"pop",
"return",
"unless",
"Fae",
".",
"languages",
".",
"has_key?",
"(",
"language_suffix",
".",
"to_sym",
")",
"||",
"Fae",
".",
"languages",
".",
"has_key?",
"(",
"language_suffix",
")",
"label",
"=",
"attribute_array",
".",
"push",
"(",
"\"(#{language_suffix})\"",
")",
".",
"join",
"(",
"' '",
")",
".",
"titleize",
"options",
"[",
":label",
"]",
"=",
"label",
"unless",
"options",
"[",
":label",
"]",
".",
"present?",
"if",
"options",
"[",
":wrapper_html",
"]",
".",
"present?",
"options",
"[",
":wrapper_html",
"]",
".",
"deep_merge!",
"(",
"{",
"data",
":",
"{",
"language",
":",
"language_suffix",
"}",
"}",
")",
"else",
"options",
"[",
":wrapper_html",
"]",
"=",
"{",
"data",
":",
"{",
"language",
":",
"language_suffix",
"}",
"}",
"end",
"end"
] |
removes language suffix from label and adds data attr for languange nav
|
[
"removes",
"language",
"suffix",
"from",
"label",
"and",
"adds",
"data",
"attr",
"for",
"languange",
"nav"
] |
645d6b66945aeff54e27af6a95c4f8a1f7a67d39
|
https://github.com/wearefine/fae/blob/645d6b66945aeff54e27af6a95c4f8a1f7a67d39/app/helpers/fae/form_helper.rb#L199-L214
|
12,667
|
wearefine/fae
|
app/controllers/concerns/fae/cloneable.rb
|
Fae.Cloneable.update_cloneable_associations
|
def update_cloneable_associations
associations_for_cloning.each do |association|
type = @klass.reflect_on_association(association)
through_record = type.through_reflection
if through_record.present?
clone_join_relationships(through_record.plural_name)
else
clone_has_one_relationship(association,type) if type.macro == :has_one
clone_has_many_relationships(association) if type.macro == :has_many
end
end
end
|
ruby
|
def update_cloneable_associations
associations_for_cloning.each do |association|
type = @klass.reflect_on_association(association)
through_record = type.through_reflection
if through_record.present?
clone_join_relationships(through_record.plural_name)
else
clone_has_one_relationship(association,type) if type.macro == :has_one
clone_has_many_relationships(association) if type.macro == :has_many
end
end
end
|
[
"def",
"update_cloneable_associations",
"associations_for_cloning",
".",
"each",
"do",
"|",
"association",
"|",
"type",
"=",
"@klass",
".",
"reflect_on_association",
"(",
"association",
")",
"through_record",
"=",
"type",
".",
"through_reflection",
"if",
"through_record",
".",
"present?",
"clone_join_relationships",
"(",
"through_record",
".",
"plural_name",
")",
"else",
"clone_has_one_relationship",
"(",
"association",
",",
"type",
")",
"if",
"type",
".",
"macro",
"==",
":has_one",
"clone_has_many_relationships",
"(",
"association",
")",
"if",
"type",
".",
"macro",
"==",
":has_many",
"end",
"end",
"end"
] |
set cloneable attributes and associations
|
[
"set",
"cloneable",
"attributes",
"and",
"associations"
] |
645d6b66945aeff54e27af6a95c4f8a1f7a67d39
|
https://github.com/wearefine/fae/blob/645d6b66945aeff54e27af6a95c4f8a1f7a67d39/app/controllers/concerns/fae/cloneable.rb#L45-L57
|
12,668
|
savonrb/savon
|
lib/savon/options.rb
|
Savon.GlobalOptions.log_level
|
def log_level(level)
levels = { :debug => 0, :info => 1, :warn => 2, :error => 3, :fatal => 4 }
unless levels.include? level
raise ArgumentError, "Invalid log level: #{level.inspect}\n" \
"Expected one of: #{levels.keys.inspect}"
end
@options[:logger].level = levels[level]
end
|
ruby
|
def log_level(level)
levels = { :debug => 0, :info => 1, :warn => 2, :error => 3, :fatal => 4 }
unless levels.include? level
raise ArgumentError, "Invalid log level: #{level.inspect}\n" \
"Expected one of: #{levels.keys.inspect}"
end
@options[:logger].level = levels[level]
end
|
[
"def",
"log_level",
"(",
"level",
")",
"levels",
"=",
"{",
":debug",
"=>",
"0",
",",
":info",
"=>",
"1",
",",
":warn",
"=>",
"2",
",",
":error",
"=>",
"3",
",",
":fatal",
"=>",
"4",
"}",
"unless",
"levels",
".",
"include?",
"level",
"raise",
"ArgumentError",
",",
"\"Invalid log level: #{level.inspect}\\n\"",
"\"Expected one of: #{levels.keys.inspect}\"",
"end",
"@options",
"[",
":logger",
"]",
".",
"level",
"=",
"levels",
"[",
"level",
"]",
"end"
] |
Changes the Logger's log level.
|
[
"Changes",
"the",
"Logger",
"s",
"log",
"level",
"."
] |
0fa08fc30ecce2cd1109474bfcc14abf13a0c297
|
https://github.com/savonrb/savon/blob/0fa08fc30ecce2cd1109474bfcc14abf13a0c297/lib/savon/options.rb#L206-L215
|
12,669
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.new_search
|
def new_search(*types, &block)
types.flatten!
search = Search::StandardSearch.new(
connection,
setup_for_types(types),
Query::StandardQuery.new(types),
@config
)
search.build(&block) if block
search
end
|
ruby
|
def new_search(*types, &block)
types.flatten!
search = Search::StandardSearch.new(
connection,
setup_for_types(types),
Query::StandardQuery.new(types),
@config
)
search.build(&block) if block
search
end
|
[
"def",
"new_search",
"(",
"*",
"types",
",",
"&",
"block",
")",
"types",
".",
"flatten!",
"search",
"=",
"Search",
"::",
"StandardSearch",
".",
"new",
"(",
"connection",
",",
"setup_for_types",
"(",
"types",
")",
",",
"Query",
"::",
"StandardQuery",
".",
"new",
"(",
"types",
")",
",",
"@config",
")",
"search",
".",
"build",
"(",
"block",
")",
"if",
"block",
"search",
"end"
] |
Sessions are initialized with a Sunspot configuration and a Solr
connection. Usually you will want to stick with the default arguments
when instantiating your own sessions.
See Sunspot.new_search
|
[
"Sessions",
"are",
"initialized",
"with",
"a",
"Sunspot",
"configuration",
"and",
"a",
"Solr",
"connection",
".",
"Usually",
"you",
"will",
"want",
"to",
"stick",
"with",
"the",
"default",
"arguments",
"when",
"instantiating",
"your",
"own",
"sessions",
"."
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L42-L52
|
12,670
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.new_more_like_this
|
def new_more_like_this(object, *types, &block)
types[0] ||= object.class
mlt = Search::MoreLikeThisSearch.new(
connection,
setup_for_types(types),
Query::MoreLikeThisQuery.new(object, types),
@config
)
mlt.build(&block) if block
mlt
end
|
ruby
|
def new_more_like_this(object, *types, &block)
types[0] ||= object.class
mlt = Search::MoreLikeThisSearch.new(
connection,
setup_for_types(types),
Query::MoreLikeThisQuery.new(object, types),
@config
)
mlt.build(&block) if block
mlt
end
|
[
"def",
"new_more_like_this",
"(",
"object",
",",
"*",
"types",
",",
"&",
"block",
")",
"types",
"[",
"0",
"]",
"||=",
"object",
".",
"class",
"mlt",
"=",
"Search",
"::",
"MoreLikeThisSearch",
".",
"new",
"(",
"connection",
",",
"setup_for_types",
"(",
"types",
")",
",",
"Query",
"::",
"MoreLikeThisQuery",
".",
"new",
"(",
"object",
",",
"types",
")",
",",
"@config",
")",
"mlt",
".",
"build",
"(",
"block",
")",
"if",
"block",
"mlt",
"end"
] |
See Sunspot.new_more_like_this
|
[
"See",
"Sunspot",
".",
"new_more_like_this"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L65-L75
|
12,671
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.more_like_this
|
def more_like_this(object, *types, &block)
mlt = new_more_like_this(object, *types, &block)
mlt.execute
end
|
ruby
|
def more_like_this(object, *types, &block)
mlt = new_more_like_this(object, *types, &block)
mlt.execute
end
|
[
"def",
"more_like_this",
"(",
"object",
",",
"*",
"types",
",",
"&",
"block",
")",
"mlt",
"=",
"new_more_like_this",
"(",
"object",
",",
"types",
",",
"block",
")",
"mlt",
".",
"execute",
"end"
] |
See Sunspot.more_like_this
|
[
"See",
"Sunspot",
".",
"more_like_this"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L80-L83
|
12,672
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.atomic_update
|
def atomic_update(clazz, updates = {})
@adds += updates.keys.length
indexer.add_atomic_update(clazz, updates)
end
|
ruby
|
def atomic_update(clazz, updates = {})
@adds += updates.keys.length
indexer.add_atomic_update(clazz, updates)
end
|
[
"def",
"atomic_update",
"(",
"clazz",
",",
"updates",
"=",
"{",
"}",
")",
"@adds",
"+=",
"updates",
".",
"keys",
".",
"length",
"indexer",
".",
"add_atomic_update",
"(",
"clazz",
",",
"updates",
")",
"end"
] |
See Sunspot.atomic_update
|
[
"See",
"Sunspot",
".",
"atomic_update"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L105-L108
|
12,673
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.remove
|
def remove(*objects, &block)
if block
types = objects
conjunction = Query::Connective::Conjunction.new
if types.length == 1
conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::EqualTo, types.first)
else
conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::AnyOf, types)
end
dsl = DSL::Scope.new(conjunction, setup_for_types(types))
Util.instance_eval_or_call(dsl, &block)
indexer.remove_by_scope(conjunction)
else
objects.flatten!
@deletes += objects.length
objects.each do |object|
indexer.remove(object)
end
end
end
|
ruby
|
def remove(*objects, &block)
if block
types = objects
conjunction = Query::Connective::Conjunction.new
if types.length == 1
conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::EqualTo, types.first)
else
conjunction.add_positive_restriction(TypeField.instance, Query::Restriction::AnyOf, types)
end
dsl = DSL::Scope.new(conjunction, setup_for_types(types))
Util.instance_eval_or_call(dsl, &block)
indexer.remove_by_scope(conjunction)
else
objects.flatten!
@deletes += objects.length
objects.each do |object|
indexer.remove(object)
end
end
end
|
[
"def",
"remove",
"(",
"*",
"objects",
",",
"&",
"block",
")",
"if",
"block",
"types",
"=",
"objects",
"conjunction",
"=",
"Query",
"::",
"Connective",
"::",
"Conjunction",
".",
"new",
"if",
"types",
".",
"length",
"==",
"1",
"conjunction",
".",
"add_positive_restriction",
"(",
"TypeField",
".",
"instance",
",",
"Query",
"::",
"Restriction",
"::",
"EqualTo",
",",
"types",
".",
"first",
")",
"else",
"conjunction",
".",
"add_positive_restriction",
"(",
"TypeField",
".",
"instance",
",",
"Query",
"::",
"Restriction",
"::",
"AnyOf",
",",
"types",
")",
"end",
"dsl",
"=",
"DSL",
"::",
"Scope",
".",
"new",
"(",
"conjunction",
",",
"setup_for_types",
"(",
"types",
")",
")",
"Util",
".",
"instance_eval_or_call",
"(",
"dsl",
",",
"block",
")",
"indexer",
".",
"remove_by_scope",
"(",
"conjunction",
")",
"else",
"objects",
".",
"flatten!",
"@deletes",
"+=",
"objects",
".",
"length",
"objects",
".",
"each",
"do",
"|",
"object",
"|",
"indexer",
".",
"remove",
"(",
"object",
")",
"end",
"end",
"end"
] |
See Sunspot.remove
|
[
"See",
"Sunspot",
".",
"remove"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L137-L156
|
12,674
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.remove_by_id
|
def remove_by_id(clazz, *ids)
class_name =
if clazz.is_a?(Class)
clazz.name
else
clazz.to_s
end
indexer.remove_by_id(class_name, ids)
end
|
ruby
|
def remove_by_id(clazz, *ids)
class_name =
if clazz.is_a?(Class)
clazz.name
else
clazz.to_s
end
indexer.remove_by_id(class_name, ids)
end
|
[
"def",
"remove_by_id",
"(",
"clazz",
",",
"*",
"ids",
")",
"class_name",
"=",
"if",
"clazz",
".",
"is_a?",
"(",
"Class",
")",
"clazz",
".",
"name",
"else",
"clazz",
".",
"to_s",
"end",
"indexer",
".",
"remove_by_id",
"(",
"class_name",
",",
"ids",
")",
"end"
] |
See Sunspot.remove_by_id
|
[
"See",
"Sunspot",
".",
"remove_by_id"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L169-L177
|
12,675
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.remove_all
|
def remove_all(*classes)
classes.flatten!
if classes.empty?
@deletes += 1
indexer.remove_all
else
@deletes += classes.length
classes.each { |clazz| indexer.remove_all(clazz) }
end
end
|
ruby
|
def remove_all(*classes)
classes.flatten!
if classes.empty?
@deletes += 1
indexer.remove_all
else
@deletes += classes.length
classes.each { |clazz| indexer.remove_all(clazz) }
end
end
|
[
"def",
"remove_all",
"(",
"*",
"classes",
")",
"classes",
".",
"flatten!",
"if",
"classes",
".",
"empty?",
"@deletes",
"+=",
"1",
"indexer",
".",
"remove_all",
"else",
"@deletes",
"+=",
"classes",
".",
"length",
"classes",
".",
"each",
"{",
"|",
"clazz",
"|",
"indexer",
".",
"remove_all",
"(",
"clazz",
")",
"}",
"end",
"end"
] |
See Sunspot.remove_all
|
[
"See",
"Sunspot",
".",
"remove_all"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L190-L199
|
12,676
|
sunspot/sunspot
|
sunspot/lib/sunspot/session.rb
|
Sunspot.Session.connection
|
def connection
@connection ||= self.class.connection_class.connect(
url: config.solr.url,
read_timeout: config.solr.read_timeout,
open_timeout: config.solr.open_timeout,
proxy: config.solr.proxy,
update_format: config.solr.update_format || :xml
)
end
|
ruby
|
def connection
@connection ||= self.class.connection_class.connect(
url: config.solr.url,
read_timeout: config.solr.read_timeout,
open_timeout: config.solr.open_timeout,
proxy: config.solr.proxy,
update_format: config.solr.update_format || :xml
)
end
|
[
"def",
"connection",
"@connection",
"||=",
"self",
".",
"class",
".",
"connection_class",
".",
"connect",
"(",
"url",
":",
"config",
".",
"solr",
".",
"url",
",",
"read_timeout",
":",
"config",
".",
"solr",
".",
"read_timeout",
",",
"open_timeout",
":",
"config",
".",
"solr",
".",
"open_timeout",
",",
"proxy",
":",
"config",
".",
"solr",
".",
"proxy",
",",
"update_format",
":",
"config",
".",
"solr",
".",
"update_format",
"||",
":xml",
")",
"end"
] |
Retrieve the Solr connection for this session, creating one if it does not
already exist.
==== Returns
RSolr::Connection::Base:: The connection for this session
|
[
"Retrieve",
"the",
"Solr",
"connection",
"for",
"this",
"session",
"creating",
"one",
"if",
"it",
"does",
"not",
"already",
"exist",
"."
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/session.rb#L256-L264
|
12,677
|
sunspot/sunspot
|
sunspot/lib/sunspot/schema.rb
|
Sunspot.Schema.dynamic_fields
|
def dynamic_fields
fields = []
variant_combinations.each do |field_variants|
FIELD_TYPES.each do |type|
fields << DynamicField.new(type, field_variants)
end
end
fields
end
|
ruby
|
def dynamic_fields
fields = []
variant_combinations.each do |field_variants|
FIELD_TYPES.each do |type|
fields << DynamicField.new(type, field_variants)
end
end
fields
end
|
[
"def",
"dynamic_fields",
"fields",
"=",
"[",
"]",
"variant_combinations",
".",
"each",
"do",
"|",
"field_variants",
"|",
"FIELD_TYPES",
".",
"each",
"do",
"|",
"type",
"|",
"fields",
"<<",
"DynamicField",
".",
"new",
"(",
"type",
",",
"field_variants",
")",
"end",
"end",
"fields",
"end"
] |
DynamicField instances representing all the available types and variants
|
[
"DynamicField",
"instances",
"representing",
"all",
"the",
"available",
"types",
"and",
"variants"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/schema.rb#L53-L61
|
12,678
|
sunspot/sunspot
|
sunspot/lib/sunspot/schema.rb
|
Sunspot.Schema.to_xml
|
def to_xml
template_path = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'schema.xml.erb')
template_text = File.read(template_path)
erb = if RUBY_VERSION >= '2.6'
ERB.new(template_text, trim_mode: '-')
else
ERB.new(template_text, nil, '-')
end
erb.result(binding)
end
|
ruby
|
def to_xml
template_path = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'schema.xml.erb')
template_text = File.read(template_path)
erb = if RUBY_VERSION >= '2.6'
ERB.new(template_text, trim_mode: '-')
else
ERB.new(template_text, nil, '-')
end
erb.result(binding)
end
|
[
"def",
"to_xml",
"template_path",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"'..'",
",",
"'..'",
",",
"'templates'",
",",
"'schema.xml.erb'",
")",
"template_text",
"=",
"File",
".",
"read",
"(",
"template_path",
")",
"erb",
"=",
"if",
"RUBY_VERSION",
">=",
"'2.6'",
"ERB",
".",
"new",
"(",
"template_text",
",",
"trim_mode",
":",
"'-'",
")",
"else",
"ERB",
".",
"new",
"(",
"template_text",
",",
"nil",
",",
"'-'",
")",
"end",
"erb",
".",
"result",
"(",
"binding",
")",
"end"
] |
Return an XML representation of this schema using the ERB template
|
[
"Return",
"an",
"XML",
"representation",
"of",
"this",
"schema",
"using",
"the",
"ERB",
"template"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/schema.rb#L90-L101
|
12,679
|
sunspot/sunspot
|
sunspot/lib/sunspot/schema.rb
|
Sunspot.Schema.variant_combinations
|
def variant_combinations
combinations = []
0.upto(2 ** FIELD_VARIANTS.length - 1) do |b|
combinations << combination = []
FIELD_VARIANTS.each_with_index do |variant, i|
combination << variant if b & 1<<i > 0
end
end
combinations
end
|
ruby
|
def variant_combinations
combinations = []
0.upto(2 ** FIELD_VARIANTS.length - 1) do |b|
combinations << combination = []
FIELD_VARIANTS.each_with_index do |variant, i|
combination << variant if b & 1<<i > 0
end
end
combinations
end
|
[
"def",
"variant_combinations",
"combinations",
"=",
"[",
"]",
"0",
".",
"upto",
"(",
"2",
"**",
"FIELD_VARIANTS",
".",
"length",
"-",
"1",
")",
"do",
"|",
"b",
"|",
"combinations",
"<<",
"combination",
"=",
"[",
"]",
"FIELD_VARIANTS",
".",
"each_with_index",
"do",
"|",
"variant",
",",
"i",
"|",
"combination",
"<<",
"variant",
"if",
"b",
"&",
"1",
"<<",
"i",
">",
"0",
"end",
"end",
"combinations",
"end"
] |
All of the possible combinations of variants
|
[
"All",
"of",
"the",
"possible",
"combinations",
"of",
"variants"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/schema.rb#L108-L117
|
12,680
|
sunspot/sunspot
|
sunspot/lib/sunspot/composite_setup.rb
|
Sunspot.CompositeSetup.text_fields
|
def text_fields(field_name)
if text_fields = text_fields_hash[field_name.to_sym]
text_fields.to_a
else
raise(
UnrecognizedFieldError,
"No text field configured for #{@types * ', '} with name '#{field_name}'"
)
end
end
|
ruby
|
def text_fields(field_name)
if text_fields = text_fields_hash[field_name.to_sym]
text_fields.to_a
else
raise(
UnrecognizedFieldError,
"No text field configured for #{@types * ', '} with name '#{field_name}'"
)
end
end
|
[
"def",
"text_fields",
"(",
"field_name",
")",
"if",
"text_fields",
"=",
"text_fields_hash",
"[",
"field_name",
".",
"to_sym",
"]",
"text_fields",
".",
"to_a",
"else",
"raise",
"(",
"UnrecognizedFieldError",
",",
"\"No text field configured for #{@types * ', '} with name '#{field_name}'\"",
")",
"end",
"end"
] |
Get a text field object by its public name. A field will be returned if
it is configured for any of the enclosed types.
==== Returns
Sunspot::FulltextField:: Text field with the given public name
==== Raises
UnrecognizedFieldError::
If no field with that name is configured for any of the enclosed types.
|
[
"Get",
"a",
"text",
"field",
"object",
"by",
"its",
"public",
"name",
".",
"A",
"field",
"will",
"be",
"returned",
"if",
"it",
"is",
"configured",
"for",
"any",
"of",
"the",
"enclosed",
"types",
"."
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/composite_setup.rb#L51-L60
|
12,681
|
sunspot/sunspot
|
sunspot/lib/sunspot/composite_setup.rb
|
Sunspot.CompositeSetup.text_fields_hash
|
def text_fields_hash
@text_fields_hash ||=
setups.inject({}) do |hash, setup|
setup.all_text_fields.each do |text_field|
(hash[text_field.name] ||= Set.new) << text_field
end
hash
end
end
|
ruby
|
def text_fields_hash
@text_fields_hash ||=
setups.inject({}) do |hash, setup|
setup.all_text_fields.each do |text_field|
(hash[text_field.name] ||= Set.new) << text_field
end
hash
end
end
|
[
"def",
"text_fields_hash",
"@text_fields_hash",
"||=",
"setups",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"hash",
",",
"setup",
"|",
"setup",
".",
"all_text_fields",
".",
"each",
"do",
"|",
"text_field",
"|",
"(",
"hash",
"[",
"text_field",
".",
"name",
"]",
"||=",
"Set",
".",
"new",
")",
"<<",
"text_field",
"end",
"hash",
"end",
"end"
] |
Return a hash of field names to text field objects, containing all fields
that are configured for any of the types enclosed.
==== Returns
Hash:: Hash of field names to text field objects.
|
[
"Return",
"a",
"hash",
"of",
"field",
"names",
"to",
"text",
"field",
"objects",
"containing",
"all",
"fields",
"that",
"are",
"configured",
"for",
"any",
"of",
"the",
"types",
"enclosed",
"."
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/composite_setup.rb#L129-L137
|
12,682
|
sunspot/sunspot
|
sunspot/lib/sunspot/composite_setup.rb
|
Sunspot.CompositeSetup.fields_hash
|
def fields_hash
@fields_hash ||=
begin
field_sets_hash = Hash.new { |h, k| h[k] = Set.new }
@types.each do |type|
Setup.for(type).fields.each do |field|
field_sets_hash[field.name.to_sym] << field
end
end
fields_hash = {}
field_sets_hash.each_pair do |field_name, set|
if set.length == 1
fields_hash[field_name] = set.to_a.first
end
end
fields_hash
end
end
|
ruby
|
def fields_hash
@fields_hash ||=
begin
field_sets_hash = Hash.new { |h, k| h[k] = Set.new }
@types.each do |type|
Setup.for(type).fields.each do |field|
field_sets_hash[field.name.to_sym] << field
end
end
fields_hash = {}
field_sets_hash.each_pair do |field_name, set|
if set.length == 1
fields_hash[field_name] = set.to_a.first
end
end
fields_hash
end
end
|
[
"def",
"fields_hash",
"@fields_hash",
"||=",
"begin",
"field_sets_hash",
"=",
"Hash",
".",
"new",
"{",
"|",
"h",
",",
"k",
"|",
"h",
"[",
"k",
"]",
"=",
"Set",
".",
"new",
"}",
"@types",
".",
"each",
"do",
"|",
"type",
"|",
"Setup",
".",
"for",
"(",
"type",
")",
".",
"fields",
".",
"each",
"do",
"|",
"field",
"|",
"field_sets_hash",
"[",
"field",
".",
"name",
".",
"to_sym",
"]",
"<<",
"field",
"end",
"end",
"fields_hash",
"=",
"{",
"}",
"field_sets_hash",
".",
"each_pair",
"do",
"|",
"field_name",
",",
"set",
"|",
"if",
"set",
".",
"length",
"==",
"1",
"fields_hash",
"[",
"field_name",
"]",
"=",
"set",
".",
"to_a",
".",
"first",
"end",
"end",
"fields_hash",
"end",
"end"
] |
Return a hash of field names to field objects, containing all fields
that are common to all of the classes enclosed. In order for fields
to be common, they must be of the same type and have the same
value for allow_multiple? and stored?. This method is memoized.
==== Returns
Hash:: field names keyed to field objects
|
[
"Return",
"a",
"hash",
"of",
"field",
"names",
"to",
"field",
"objects",
"containing",
"all",
"fields",
"that",
"are",
"common",
"to",
"all",
"of",
"the",
"classes",
"enclosed",
".",
"In",
"order",
"for",
"fields",
"to",
"be",
"common",
"they",
"must",
"be",
"of",
"the",
"same",
"type",
"and",
"have",
"the",
"same",
"value",
"for",
"allow_multiple?",
"and",
"stored?",
".",
"This",
"method",
"is",
"memoized",
"."
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/composite_setup.rb#L159-L176
|
12,683
|
sunspot/sunspot
|
sunspot/lib/sunspot/setup.rb
|
Sunspot.Setup.add_text_field_factory
|
def add_text_field_factory(name, options = {}, &block)
stored, more_like_this = options[:stored], options[:more_like_this]
field_factory = FieldFactory::Static.new(name, Type::TextType.instance, options, &block)
@text_field_factories[name] = field_factory
@text_field_factories_cache[field_factory.name] = field_factory
if stored
@stored_field_factories_cache[field_factory.name] << field_factory
end
if more_like_this
@more_like_this_field_factories_cache[field_factory.name] << field_factory
end
end
|
ruby
|
def add_text_field_factory(name, options = {}, &block)
stored, more_like_this = options[:stored], options[:more_like_this]
field_factory = FieldFactory::Static.new(name, Type::TextType.instance, options, &block)
@text_field_factories[name] = field_factory
@text_field_factories_cache[field_factory.name] = field_factory
if stored
@stored_field_factories_cache[field_factory.name] << field_factory
end
if more_like_this
@more_like_this_field_factories_cache[field_factory.name] << field_factory
end
end
|
[
"def",
"add_text_field_factory",
"(",
"name",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"stored",
",",
"more_like_this",
"=",
"options",
"[",
":stored",
"]",
",",
"options",
"[",
":more_like_this",
"]",
"field_factory",
"=",
"FieldFactory",
"::",
"Static",
".",
"new",
"(",
"name",
",",
"Type",
"::",
"TextType",
".",
"instance",
",",
"options",
",",
"block",
")",
"@text_field_factories",
"[",
"name",
"]",
"=",
"field_factory",
"@text_field_factories_cache",
"[",
"field_factory",
".",
"name",
"]",
"=",
"field_factory",
"if",
"stored",
"@stored_field_factories_cache",
"[",
"field_factory",
".",
"name",
"]",
"<<",
"field_factory",
"end",
"if",
"more_like_this",
"@more_like_this_field_factories_cache",
"[",
"field_factory",
".",
"name",
"]",
"<<",
"field_factory",
"end",
"end"
] |
Add field_factories for fulltext search
==== Parameters
field_factories<Array>:: Array of Sunspot::Field objects
|
[
"Add",
"field_factories",
"for",
"fulltext",
"search"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/setup.rb#L59-L70
|
12,684
|
sunspot/sunspot
|
sunspot/lib/sunspot/setup.rb
|
Sunspot.Setup.add_dynamic_field_factory
|
def add_dynamic_field_factory(name, type, options = {}, &block)
stored, more_like_this = options[:stored], options[:more_like_this]
field_factory = FieldFactory::Dynamic.new(name, type, options, &block)
@dynamic_field_factories[field_factory.signature] = field_factory
@dynamic_field_factories_cache[field_factory.name] = field_factory
if stored
@stored_field_factories_cache[field_factory.name] << field_factory
end
if more_like_this
@more_like_this_field_factories_cache[field_factory.name] << field_factory
end
end
|
ruby
|
def add_dynamic_field_factory(name, type, options = {}, &block)
stored, more_like_this = options[:stored], options[:more_like_this]
field_factory = FieldFactory::Dynamic.new(name, type, options, &block)
@dynamic_field_factories[field_factory.signature] = field_factory
@dynamic_field_factories_cache[field_factory.name] = field_factory
if stored
@stored_field_factories_cache[field_factory.name] << field_factory
end
if more_like_this
@more_like_this_field_factories_cache[field_factory.name] << field_factory
end
end
|
[
"def",
"add_dynamic_field_factory",
"(",
"name",
",",
"type",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"stored",
",",
"more_like_this",
"=",
"options",
"[",
":stored",
"]",
",",
"options",
"[",
":more_like_this",
"]",
"field_factory",
"=",
"FieldFactory",
"::",
"Dynamic",
".",
"new",
"(",
"name",
",",
"type",
",",
"options",
",",
"block",
")",
"@dynamic_field_factories",
"[",
"field_factory",
".",
"signature",
"]",
"=",
"field_factory",
"@dynamic_field_factories_cache",
"[",
"field_factory",
".",
"name",
"]",
"=",
"field_factory",
"if",
"stored",
"@stored_field_factories_cache",
"[",
"field_factory",
".",
"name",
"]",
"<<",
"field_factory",
"end",
"if",
"more_like_this",
"@more_like_this_field_factories_cache",
"[",
"field_factory",
".",
"name",
"]",
"<<",
"field_factory",
"end",
"end"
] |
Add dynamic field_factories
==== Parameters
field_factories<Array>:: Array of dynamic field objects
|
[
"Add",
"dynamic",
"field_factories"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/setup.rb#L79-L90
|
12,685
|
sunspot/sunspot
|
sunspot/lib/sunspot/setup.rb
|
Sunspot.Setup.all_more_like_this_fields
|
def all_more_like_this_fields
@more_like_this_field_factories_cache.values.map do |field_factories|
field_factories.map { |field_factory| field_factory.build }
end.flatten
end
|
ruby
|
def all_more_like_this_fields
@more_like_this_field_factories_cache.values.map do |field_factories|
field_factories.map { |field_factory| field_factory.build }
end.flatten
end
|
[
"def",
"all_more_like_this_fields",
"@more_like_this_field_factories_cache",
".",
"values",
".",
"map",
"do",
"|",
"field_factories",
"|",
"field_factories",
".",
"map",
"{",
"|",
"field_factory",
"|",
"field_factory",
".",
"build",
"}",
"end",
".",
"flatten",
"end"
] |
Return all more_like_this fields
|
[
"Return",
"all",
"more_like_this",
"fields"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/setup.rb#L200-L204
|
12,686
|
sunspot/sunspot
|
sunspot/lib/sunspot/setup.rb
|
Sunspot.Setup.all_field_factories
|
def all_field_factories
all_field_factories = []
all_field_factories.concat(field_factories).concat(text_field_factories).concat(dynamic_field_factories)
all_field_factories
end
|
ruby
|
def all_field_factories
all_field_factories = []
all_field_factories.concat(field_factories).concat(text_field_factories).concat(dynamic_field_factories)
all_field_factories
end
|
[
"def",
"all_field_factories",
"all_field_factories",
"=",
"[",
"]",
"all_field_factories",
".",
"concat",
"(",
"field_factories",
")",
".",
"concat",
"(",
"text_field_factories",
")",
".",
"concat",
"(",
"dynamic_field_factories",
")",
"all_field_factories",
"end"
] |
Get all static, dynamic, and text field_factories associated with this setup as
well as all inherited field_factories
==== Returns
Array:: Collection of all text and scope field_factories associated with this setup
|
[
"Get",
"all",
"static",
"dynamic",
"and",
"text",
"field_factories",
"associated",
"with",
"this",
"setup",
"as",
"well",
"as",
"all",
"inherited",
"field_factories"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/setup.rb#L237-L241
|
12,687
|
sunspot/sunspot
|
sunspot/lib/sunspot/indexer.rb
|
Sunspot.Indexer.add_atomic_update
|
def add_atomic_update(clazz, updates={})
documents = updates.map { |id, m| prepare_atomic_update(clazz, id, m) }
add_batch_documents(documents)
end
|
ruby
|
def add_atomic_update(clazz, updates={})
documents = updates.map { |id, m| prepare_atomic_update(clazz, id, m) }
add_batch_documents(documents)
end
|
[
"def",
"add_atomic_update",
"(",
"clazz",
",",
"updates",
"=",
"{",
"}",
")",
"documents",
"=",
"updates",
".",
"map",
"{",
"|",
"id",
",",
"m",
"|",
"prepare_atomic_update",
"(",
"clazz",
",",
"id",
",",
"m",
")",
"}",
"add_batch_documents",
"(",
"documents",
")",
"end"
] |
Construct a representation of the given class instances for atomic properties update
and send it to the connection for indexing
==== Parameters
clazz<Class>:: the class of the models to be updated
updates<Hash>:: hash of updates where keys are model ids
and values are hash with property name/values to be updated
|
[
"Construct",
"a",
"representation",
"of",
"the",
"given",
"class",
"instances",
"for",
"atomic",
"properties",
"update",
"and",
"send",
"it",
"to",
"the",
"connection",
"for",
"indexing"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/indexer.rb#L39-L42
|
12,688
|
sunspot/sunspot
|
sunspot/lib/sunspot/indexer.rb
|
Sunspot.Indexer.remove
|
def remove(*models)
@connection.delete_by_id(
models.map { |model| Adapters::InstanceAdapter.adapt(model).index_id }
)
end
|
ruby
|
def remove(*models)
@connection.delete_by_id(
models.map { |model| Adapters::InstanceAdapter.adapt(model).index_id }
)
end
|
[
"def",
"remove",
"(",
"*",
"models",
")",
"@connection",
".",
"delete_by_id",
"(",
"models",
".",
"map",
"{",
"|",
"model",
"|",
"Adapters",
"::",
"InstanceAdapter",
".",
"adapt",
"(",
"model",
")",
".",
"index_id",
"}",
")",
"end"
] |
Remove the given model from the Solr index
|
[
"Remove",
"the",
"given",
"model",
"from",
"the",
"Solr",
"index"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/indexer.rb#L47-L51
|
12,689
|
sunspot/sunspot
|
sunspot/lib/sunspot/indexer.rb
|
Sunspot.Indexer.remove_by_id
|
def remove_by_id(class_name, *ids)
ids.flatten!
@connection.delete_by_id(
ids.map { |id| Adapters::InstanceAdapter.index_id_for(class_name, id) }
)
end
|
ruby
|
def remove_by_id(class_name, *ids)
ids.flatten!
@connection.delete_by_id(
ids.map { |id| Adapters::InstanceAdapter.index_id_for(class_name, id) }
)
end
|
[
"def",
"remove_by_id",
"(",
"class_name",
",",
"*",
"ids",
")",
"ids",
".",
"flatten!",
"@connection",
".",
"delete_by_id",
"(",
"ids",
".",
"map",
"{",
"|",
"id",
"|",
"Adapters",
"::",
"InstanceAdapter",
".",
"index_id_for",
"(",
"class_name",
",",
"id",
")",
"}",
")",
"end"
] |
Remove the model from the Solr index by specifying the class and ID
|
[
"Remove",
"the",
"model",
"from",
"the",
"Solr",
"index",
"by",
"specifying",
"the",
"class",
"and",
"ID"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/indexer.rb#L56-L61
|
12,690
|
sunspot/sunspot
|
sunspot/lib/sunspot/indexer.rb
|
Sunspot.Indexer.prepare_full_update
|
def prepare_full_update(model)
document = document_for_full_update(model)
setup = setup_for_object(model)
if boost = setup.document_boost_for(model)
document.attrs[:boost] = boost
end
setup.all_field_factories.each do |field_factory|
field_factory.populate_document(document, model)
end
document
end
|
ruby
|
def prepare_full_update(model)
document = document_for_full_update(model)
setup = setup_for_object(model)
if boost = setup.document_boost_for(model)
document.attrs[:boost] = boost
end
setup.all_field_factories.each do |field_factory|
field_factory.populate_document(document, model)
end
document
end
|
[
"def",
"prepare_full_update",
"(",
"model",
")",
"document",
"=",
"document_for_full_update",
"(",
"model",
")",
"setup",
"=",
"setup_for_object",
"(",
"model",
")",
"if",
"boost",
"=",
"setup",
".",
"document_boost_for",
"(",
"model",
")",
"document",
".",
"attrs",
"[",
":boost",
"]",
"=",
"boost",
"end",
"setup",
".",
"all_field_factories",
".",
"each",
"do",
"|",
"field_factory",
"|",
"field_factory",
".",
"populate_document",
"(",
"document",
",",
"model",
")",
"end",
"document",
"end"
] |
Convert documents into hash of indexed properties
|
[
"Convert",
"documents",
"into",
"hash",
"of",
"indexed",
"properties"
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/indexer.rb#L104-L114
|
12,691
|
sunspot/sunspot
|
sunspot/lib/sunspot/indexer.rb
|
Sunspot.Indexer.document_for_full_update
|
def document_for_full_update(model)
RSolr::Xml::Document.new(
id: Adapters::InstanceAdapter.adapt(model).index_id,
type: Util.superclasses_for(model.class).map(&:name)
)
end
|
ruby
|
def document_for_full_update(model)
RSolr::Xml::Document.new(
id: Adapters::InstanceAdapter.adapt(model).index_id,
type: Util.superclasses_for(model.class).map(&:name)
)
end
|
[
"def",
"document_for_full_update",
"(",
"model",
")",
"RSolr",
"::",
"Xml",
"::",
"Document",
".",
"new",
"(",
"id",
":",
"Adapters",
"::",
"InstanceAdapter",
".",
"adapt",
"(",
"model",
")",
".",
"index_id",
",",
"type",
":",
"Util",
".",
"superclasses_for",
"(",
"model",
".",
"class",
")",
".",
"map",
"(",
":name",
")",
")",
"end"
] |
All indexed documents index and store the +id+ and +type+ fields.
These methods construct the document hash containing those key-value
pairs.
|
[
"All",
"indexed",
"documents",
"index",
"and",
"store",
"the",
"+",
"id",
"+",
"and",
"+",
"type",
"+",
"fields",
".",
"These",
"methods",
"construct",
"the",
"document",
"hash",
"containing",
"those",
"key",
"-",
"value",
"pairs",
"."
] |
31dd76cd7a14a4ef7bd541de97483d8cd72ff685
|
https://github.com/sunspot/sunspot/blob/31dd76cd7a14a4ef7bd541de97483d8cd72ff685/sunspot/lib/sunspot/indexer.rb#L143-L148
|
12,692
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.analyze
|
def analyze(phone, passed_country)
country = country_or_default_country passed_country
result = parse_country(phone, country)
d_result = case
when result && result.values.find { |e| e[:valid].any? }
# all is good, return result
when passed_country.nil?
# trying for all countries if no country was passed
detect_and_parse(phone, country)
when country_can_dp?(country)
# if country allows double prefix trying modified phone
parse_country(changed_dp_phone(country, phone), country)
end
better_result(result, d_result)
end
|
ruby
|
def analyze(phone, passed_country)
country = country_or_default_country passed_country
result = parse_country(phone, country)
d_result = case
when result && result.values.find { |e| e[:valid].any? }
# all is good, return result
when passed_country.nil?
# trying for all countries if no country was passed
detect_and_parse(phone, country)
when country_can_dp?(country)
# if country allows double prefix trying modified phone
parse_country(changed_dp_phone(country, phone), country)
end
better_result(result, d_result)
end
|
[
"def",
"analyze",
"(",
"phone",
",",
"passed_country",
")",
"country",
"=",
"country_or_default_country",
"passed_country",
"result",
"=",
"parse_country",
"(",
"phone",
",",
"country",
")",
"d_result",
"=",
"case",
"when",
"result",
"&&",
"result",
".",
"values",
".",
"find",
"{",
"|",
"e",
"|",
"e",
"[",
":valid",
"]",
".",
"any?",
"}",
"# all is good, return result",
"when",
"passed_country",
".",
"nil?",
"# trying for all countries if no country was passed",
"detect_and_parse",
"(",
"phone",
",",
"country",
")",
"when",
"country_can_dp?",
"(",
"country",
")",
"# if country allows double prefix trying modified phone",
"parse_country",
"(",
"changed_dp_phone",
"(",
"country",
",",
"phone",
")",
",",
"country",
")",
"end",
"better_result",
"(",
"result",
",",
"d_result",
")",
"end"
] |
parses provided phone if it is valid for country data and
returns result of analyze
==== Attributes
* +phone+ - Phone number for parsing
* +passed_country+ - Country provided for parsing. Must be ISO code of
country (2 letters) like 'US', 'us' or :us for United States
|
[
"parses",
"provided",
"phone",
"if",
"it",
"is",
"valid",
"for",
"country",
"data",
"and",
"returns",
"result",
"of",
"analyze"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L18-L33
|
12,693
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.better_result
|
def better_result(base_result, result = nil)
base_result ||= {}
return base_result unless result
return result unless base_result.values.find { |e| e[:possible].any? }
return result if result.values.find { |e| e[:valid].any? }
base_result
end
|
ruby
|
def better_result(base_result, result = nil)
base_result ||= {}
return base_result unless result
return result unless base_result.values.find { |e| e[:possible].any? }
return result if result.values.find { |e| e[:valid].any? }
base_result
end
|
[
"def",
"better_result",
"(",
"base_result",
",",
"result",
"=",
"nil",
")",
"base_result",
"||=",
"{",
"}",
"return",
"base_result",
"unless",
"result",
"return",
"result",
"unless",
"base_result",
".",
"values",
".",
"find",
"{",
"|",
"e",
"|",
"e",
"[",
":possible",
"]",
".",
"any?",
"}",
"return",
"result",
"if",
"result",
".",
"values",
".",
"find",
"{",
"|",
"e",
"|",
"e",
"[",
":valid",
"]",
".",
"any?",
"}",
"base_result",
"end"
] |
method checks which result is better to return
|
[
"method",
"checks",
"which",
"result",
"is",
"better",
"to",
"return"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L38-L47
|
12,694
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.with_replaced_national_prefix
|
def with_replaced_national_prefix(phone, data)
return phone unless data[Core::NATIONAL_PREFIX_TRANSFORM_RULE]
pattern = cr("^(?:#{data[Core::NATIONAL_PREFIX_FOR_PARSING]})")
match = phone.match pattern
if match && match.captures.compact.size > 0
phone.gsub(pattern, data[Core::NATIONAL_PREFIX_TRANSFORM_RULE])
else
phone
end
end
|
ruby
|
def with_replaced_national_prefix(phone, data)
return phone unless data[Core::NATIONAL_PREFIX_TRANSFORM_RULE]
pattern = cr("^(?:#{data[Core::NATIONAL_PREFIX_FOR_PARSING]})")
match = phone.match pattern
if match && match.captures.compact.size > 0
phone.gsub(pattern, data[Core::NATIONAL_PREFIX_TRANSFORM_RULE])
else
phone
end
end
|
[
"def",
"with_replaced_national_prefix",
"(",
"phone",
",",
"data",
")",
"return",
"phone",
"unless",
"data",
"[",
"Core",
"::",
"NATIONAL_PREFIX_TRANSFORM_RULE",
"]",
"pattern",
"=",
"cr",
"(",
"\"^(?:#{data[Core::NATIONAL_PREFIX_FOR_PARSING]})\"",
")",
"match",
"=",
"phone",
".",
"match",
"pattern",
"if",
"match",
"&&",
"match",
".",
"captures",
".",
"compact",
".",
"size",
">",
"0",
"phone",
".",
"gsub",
"(",
"pattern",
",",
"data",
"[",
"Core",
"::",
"NATIONAL_PREFIX_TRANSFORM_RULE",
"]",
")",
"else",
"phone",
"end",
"end"
] |
replacing national prefix to simplified format
|
[
"replacing",
"national",
"prefix",
"to",
"simplified",
"format"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L50-L59
|
12,695
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.parse_country
|
def parse_country(phone, country)
data = Phonelib.phone_data[country]
return nil unless data
# if country was provided and it's a valid country, trying to
# create e164 representation of phone number,
# kind of normalization for parsing
e164 = convert_to_e164 with_replaced_national_prefix(phone, data), data
# if phone starts with international prefix of provided
# country try to reanalyze without international prefix for
# all countries
return analyze(e164[1..-1], nil) if Core::PLUS_SIGN == e164[0]
# trying to parse number for provided country
parse_single_country e164, data
end
|
ruby
|
def parse_country(phone, country)
data = Phonelib.phone_data[country]
return nil unless data
# if country was provided and it's a valid country, trying to
# create e164 representation of phone number,
# kind of normalization for parsing
e164 = convert_to_e164 with_replaced_national_prefix(phone, data), data
# if phone starts with international prefix of provided
# country try to reanalyze without international prefix for
# all countries
return analyze(e164[1..-1], nil) if Core::PLUS_SIGN == e164[0]
# trying to parse number for provided country
parse_single_country e164, data
end
|
[
"def",
"parse_country",
"(",
"phone",
",",
"country",
")",
"data",
"=",
"Phonelib",
".",
"phone_data",
"[",
"country",
"]",
"return",
"nil",
"unless",
"data",
"# if country was provided and it's a valid country, trying to",
"# create e164 representation of phone number,",
"# kind of normalization for parsing",
"e164",
"=",
"convert_to_e164",
"with_replaced_national_prefix",
"(",
"phone",
",",
"data",
")",
",",
"data",
"# if phone starts with international prefix of provided",
"# country try to reanalyze without international prefix for",
"# all countries",
"return",
"analyze",
"(",
"e164",
"[",
"1",
"..",
"-",
"1",
"]",
",",
"nil",
")",
"if",
"Core",
"::",
"PLUS_SIGN",
"==",
"e164",
"[",
"0",
"]",
"# trying to parse number for provided country",
"parse_single_country",
"e164",
",",
"data",
"end"
] |
trying to parse phone for single country including international prefix
check for provided country
==== Attributes
* +phone+ - phone for parsing
* +country+ - country to parse phone with
|
[
"trying",
"to",
"parse",
"phone",
"for",
"single",
"country",
"including",
"international",
"prefix",
"check",
"for",
"provided",
"country"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L68-L82
|
12,696
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.parse_single_country
|
def parse_single_country(e164, data)
valid_match = phone_match_data?(e164, data)
if valid_match
national_and_data(data, valid_match)
else
possible_match = phone_match_data?(e164, data, true)
possible_match && national_and_data(data, possible_match, true)
end
end
|
ruby
|
def parse_single_country(e164, data)
valid_match = phone_match_data?(e164, data)
if valid_match
national_and_data(data, valid_match)
else
possible_match = phone_match_data?(e164, data, true)
possible_match && national_and_data(data, possible_match, true)
end
end
|
[
"def",
"parse_single_country",
"(",
"e164",
",",
"data",
")",
"valid_match",
"=",
"phone_match_data?",
"(",
"e164",
",",
"data",
")",
"if",
"valid_match",
"national_and_data",
"(",
"data",
",",
"valid_match",
")",
"else",
"possible_match",
"=",
"phone_match_data?",
"(",
"e164",
",",
"data",
",",
"true",
")",
"possible_match",
"&&",
"national_and_data",
"(",
"data",
",",
"possible_match",
",",
"true",
")",
"end",
"end"
] |
method checks if phone is valid against single provided country data
==== Attributes
* +e164+ - e164 representation of phone for parsing
* +data+ - country data for single country for parsing
|
[
"method",
"checks",
"if",
"phone",
"is",
"valid",
"against",
"single",
"provided",
"country",
"data"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L90-L98
|
12,697
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.detect_and_parse
|
def detect_and_parse(phone, country)
result = {}
Phonelib.phone_data.each do |key, data|
parsed = parse_single_country(phone, data)
if (!Phonelib.strict_double_prefix_check || key == country) && double_prefix_allowed?(data, phone, parsed && parsed[key])
parsed = parse_single_country(changed_dp_phone(key, phone), data)
end
result.merge!(parsed) unless parsed.nil?
end
result
end
|
ruby
|
def detect_and_parse(phone, country)
result = {}
Phonelib.phone_data.each do |key, data|
parsed = parse_single_country(phone, data)
if (!Phonelib.strict_double_prefix_check || key == country) && double_prefix_allowed?(data, phone, parsed && parsed[key])
parsed = parse_single_country(changed_dp_phone(key, phone), data)
end
result.merge!(parsed) unless parsed.nil?
end
result
end
|
[
"def",
"detect_and_parse",
"(",
"phone",
",",
"country",
")",
"result",
"=",
"{",
"}",
"Phonelib",
".",
"phone_data",
".",
"each",
"do",
"|",
"key",
",",
"data",
"|",
"parsed",
"=",
"parse_single_country",
"(",
"phone",
",",
"data",
")",
"if",
"(",
"!",
"Phonelib",
".",
"strict_double_prefix_check",
"||",
"key",
"==",
"country",
")",
"&&",
"double_prefix_allowed?",
"(",
"data",
",",
"phone",
",",
"parsed",
"&&",
"parsed",
"[",
"key",
"]",
")",
"parsed",
"=",
"parse_single_country",
"(",
"changed_dp_phone",
"(",
"key",
",",
"phone",
")",
",",
"data",
")",
"end",
"result",
".",
"merge!",
"(",
"parsed",
")",
"unless",
"parsed",
".",
"nil?",
"end",
"result",
"end"
] |
method tries to detect what is the country for provided phone
==== Attributes
* +phone+ - phone number for parsing
|
[
"method",
"tries",
"to",
"detect",
"what",
"is",
"the",
"country",
"for",
"provided",
"phone"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L105-L115
|
12,698
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.convert_to_e164
|
def convert_to_e164(phone, data)
match = phone.match full_regex_for_data(data, Core::VALID_PATTERN, !original_starts_with_plus?)
case
when match
"#{data[Core::COUNTRY_CODE]}#{match.to_a.last}"
when phone.match(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"))
phone.sub(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"), Core::PLUS_SIGN)
when original_starts_with_plus? && phone.start_with?(data[Core::COUNTRY_CODE])
phone
else
"#{data[Core::COUNTRY_CODE]}#{phone}"
end
end
|
ruby
|
def convert_to_e164(phone, data)
match = phone.match full_regex_for_data(data, Core::VALID_PATTERN, !original_starts_with_plus?)
case
when match
"#{data[Core::COUNTRY_CODE]}#{match.to_a.last}"
when phone.match(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"))
phone.sub(cr("^#{data[Core::INTERNATIONAL_PREFIX]}"), Core::PLUS_SIGN)
when original_starts_with_plus? && phone.start_with?(data[Core::COUNTRY_CODE])
phone
else
"#{data[Core::COUNTRY_CODE]}#{phone}"
end
end
|
[
"def",
"convert_to_e164",
"(",
"phone",
",",
"data",
")",
"match",
"=",
"phone",
".",
"match",
"full_regex_for_data",
"(",
"data",
",",
"Core",
"::",
"VALID_PATTERN",
",",
"!",
"original_starts_with_plus?",
")",
"case",
"when",
"match",
"\"#{data[Core::COUNTRY_CODE]}#{match.to_a.last}\"",
"when",
"phone",
".",
"match",
"(",
"cr",
"(",
"\"^#{data[Core::INTERNATIONAL_PREFIX]}\"",
")",
")",
"phone",
".",
"sub",
"(",
"cr",
"(",
"\"^#{data[Core::INTERNATIONAL_PREFIX]}\"",
")",
",",
"Core",
"::",
"PLUS_SIGN",
")",
"when",
"original_starts_with_plus?",
"&&",
"phone",
".",
"start_with?",
"(",
"data",
"[",
"Core",
"::",
"COUNTRY_CODE",
"]",
")",
"phone",
"else",
"\"#{data[Core::COUNTRY_CODE]}#{phone}\"",
"end",
"end"
] |
Create phone representation in e164 format
==== Attributes
* +phone+ - phone number for parsing
* +data+ - country data to be based on for creating e164 representation
|
[
"Create",
"phone",
"representation",
"in",
"e164",
"format"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L123-L135
|
12,699
|
daddyz/phonelib
|
lib/phonelib/phone_analyzer.rb
|
Phonelib.PhoneAnalyzer.national_and_data
|
def national_and_data(data, country_match, not_valid = false)
result = data.select { |k, _v| k != :types && k != :formats }
phone = country_match.to_a.last
result[:national] = phone
result[:format] = number_format(phone, data[Core::FORMATS])
result.merge! all_number_types(phone, data[Core::TYPES], not_valid)
result[:valid] = [] if not_valid
{ result[:id] => result }
end
|
ruby
|
def national_and_data(data, country_match, not_valid = false)
result = data.select { |k, _v| k != :types && k != :formats }
phone = country_match.to_a.last
result[:national] = phone
result[:format] = number_format(phone, data[Core::FORMATS])
result.merge! all_number_types(phone, data[Core::TYPES], not_valid)
result[:valid] = [] if not_valid
{ result[:id] => result }
end
|
[
"def",
"national_and_data",
"(",
"data",
",",
"country_match",
",",
"not_valid",
"=",
"false",
")",
"result",
"=",
"data",
".",
"select",
"{",
"|",
"k",
",",
"_v",
"|",
"k",
"!=",
":types",
"&&",
"k",
"!=",
":formats",
"}",
"phone",
"=",
"country_match",
".",
"to_a",
".",
"last",
"result",
"[",
":national",
"]",
"=",
"phone",
"result",
"[",
":format",
"]",
"=",
"number_format",
"(",
"phone",
",",
"data",
"[",
"Core",
"::",
"FORMATS",
"]",
")",
"result",
".",
"merge!",
"all_number_types",
"(",
"phone",
",",
"data",
"[",
"Core",
"::",
"TYPES",
"]",
",",
"not_valid",
")",
"result",
"[",
":valid",
"]",
"=",
"[",
"]",
"if",
"not_valid",
"{",
"result",
"[",
":id",
"]",
"=>",
"result",
"}",
"end"
] |
returns national number and analyzing results for provided phone number
==== Attributes
* +data+ - country data
* +country_match+ - result of match of phone within full regex
* +not_valid+ - specifies that number is not valid by general desc pattern
|
[
"returns",
"national",
"number",
"and",
"analyzing",
"results",
"for",
"provided",
"phone",
"number"
] |
aa0023eab7c896b71275bf342bc7f49735cbdbbf
|
https://github.com/daddyz/phonelib/blob/aa0023eab7c896b71275bf342bc7f49735cbdbbf/lib/phonelib/phone_analyzer.rb#L144-L153
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.