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
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/recorder.rb | XRay.Recorder.capture | def capture(name, namespace: nil, segment: nil)
subsegment = begin_subsegment name, namespace: namespace, segment: segment
# prevent passed block from failing in case of context missing with log error
if subsegment.nil?
segment = DummySegment.new name: name
subsegment = DummySubsegment.new name: name, segment: segment
end
begin
yield subsegment
rescue Exception => e
subsegment.add_exception exception: e
raise e
ensure
end_subsegment
end
end | ruby | def capture(name, namespace: nil, segment: nil)
subsegment = begin_subsegment name, namespace: namespace, segment: segment
# prevent passed block from failing in case of context missing with log error
if subsegment.nil?
segment = DummySegment.new name: name
subsegment = DummySubsegment.new name: name, segment: segment
end
begin
yield subsegment
rescue Exception => e
subsegment.add_exception exception: e
raise e
ensure
end_subsegment
end
end | [
"def",
"capture",
"(",
"name",
",",
"namespace",
":",
"nil",
",",
"segment",
":",
"nil",
")",
"subsegment",
"=",
"begin_subsegment",
"name",
",",
"namespace",
":",
"namespace",
",",
"segment",
":",
"segment",
"# prevent passed block from failing in case of context missing with log error",
"if",
"subsegment",
".",
"nil?",
"segment",
"=",
"DummySegment",
".",
"new",
"name",
":",
"name",
"subsegment",
"=",
"DummySubsegment",
".",
"new",
"name",
":",
"name",
",",
"segment",
":",
"segment",
"end",
"begin",
"yield",
"subsegment",
"rescue",
"Exception",
"=>",
"e",
"subsegment",
".",
"add_exception",
"exception",
":",
"e",
"raise",
"e",
"ensure",
"end_subsegment",
"end",
"end"
] | Record the passed block as a subsegment.
If `context_missing` is set to `LOG_ERROR` and no active entity can be found,
the passed block will be executed as normal but it will not be recorded. | [
"Record",
"the",
"passed",
"block",
"as",
"a",
"subsegment",
".",
"If",
"context_missing",
"is",
"set",
"to",
"LOG_ERROR",
"and",
"no",
"active",
"entity",
"can",
"be",
"found",
"the",
"passed",
"block",
"will",
"be",
"executed",
"as",
"normal",
"but",
"it",
"will",
"not",
"be",
"recorded",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/recorder.rb#L112-L128 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/recorder.rb | XRay.Recorder.metadata | def metadata(namespace: :default)
entity = current_entity
if entity
entity.metadata(namespace: namespace)
else
FacadeMetadata
end
end | ruby | def metadata(namespace: :default)
entity = current_entity
if entity
entity.metadata(namespace: namespace)
else
FacadeMetadata
end
end | [
"def",
"metadata",
"(",
"namespace",
":",
":default",
")",
"entity",
"=",
"current_entity",
"if",
"entity",
"entity",
".",
"metadata",
"(",
"namespace",
":",
"namespace",
")",
"else",
"FacadeMetadata",
"end",
"end"
] | A proxy method to get the metadata under provided namespace
from the current active entity. | [
"A",
"proxy",
"method",
"to",
"get",
"the",
"metadata",
"under",
"provided",
"namespace",
"from",
"the",
"current",
"active",
"entity",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/recorder.rb#L168-L175 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/sampling/reservoir.rb | XRay.Reservoir.borrow_or_take | def borrow_or_take(now, borrowable)
@lock.synchronize do
reset_new_sec(now)
# Don't borrow if the quota is available and fresh.
if quota_fresh?(now)
return SamplingDecision::NOT_SAMPLE if @taken_this_sec >= @quota
@taken_this_sec += 1
return SamplingDecision::TAKE
end
# Otherwise try to borrow if the quota is not present or expired.
if borrowable
return SamplingDecision::NOT_SAMPLE if @borrowed_this_sec >= 1
@borrowed_this_sec += 1
return SamplingDecision::BORROW
end
# Cannot sample if quota expires and cannot borrow
SamplingDecision::NOT_SAMPLE
end
end | ruby | def borrow_or_take(now, borrowable)
@lock.synchronize do
reset_new_sec(now)
# Don't borrow if the quota is available and fresh.
if quota_fresh?(now)
return SamplingDecision::NOT_SAMPLE if @taken_this_sec >= @quota
@taken_this_sec += 1
return SamplingDecision::TAKE
end
# Otherwise try to borrow if the quota is not present or expired.
if borrowable
return SamplingDecision::NOT_SAMPLE if @borrowed_this_sec >= 1
@borrowed_this_sec += 1
return SamplingDecision::BORROW
end
# Cannot sample if quota expires and cannot borrow
SamplingDecision::NOT_SAMPLE
end
end | [
"def",
"borrow_or_take",
"(",
"now",
",",
"borrowable",
")",
"@lock",
".",
"synchronize",
"do",
"reset_new_sec",
"(",
"now",
")",
"# Don't borrow if the quota is available and fresh.",
"if",
"quota_fresh?",
"(",
"now",
")",
"return",
"SamplingDecision",
"::",
"NOT_SAMPLE",
"if",
"@taken_this_sec",
">=",
"@quota",
"@taken_this_sec",
"+=",
"1",
"return",
"SamplingDecision",
"::",
"TAKE",
"end",
"# Otherwise try to borrow if the quota is not present or expired.",
"if",
"borrowable",
"return",
"SamplingDecision",
"::",
"NOT_SAMPLE",
"if",
"@borrowed_this_sec",
">=",
"1",
"@borrowed_this_sec",
"+=",
"1",
"return",
"SamplingDecision",
"::",
"BORROW",
"end",
"# Cannot sample if quota expires and cannot borrow",
"SamplingDecision",
"::",
"NOT_SAMPLE",
"end",
"end"
] | Decide whether to borrow or take one quota from
the reservoir. Return `false` if it can neither
borrow nor take. This method is thread-safe. | [
"Decide",
"whether",
"to",
"borrow",
"or",
"take",
"one",
"quota",
"from",
"the",
"reservoir",
".",
"Return",
"false",
"if",
"it",
"can",
"neither",
"borrow",
"nor",
"take",
".",
"This",
"method",
"is",
"thread",
"-",
"safe",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/sampling/reservoir.rb#L27-L47 | train |
aws/aws-xray-sdk-ruby | lib/aws-xray-sdk/sampling/default_sampler.rb | XRay.DefaultSampler.sample_request? | def sample_request?(sampling_req)
start unless @started
now = Time.now.to_i
if sampling_req.nil?
sampling_req = { service_type: @origin } if @origin
elsif !sampling_req.key?(:service_type)
sampling_req[:service_type] = @origin if @origin
end
matched_rule = @cache.get_matched_rule(sampling_req, now: now)
if !matched_rule.nil?
logger.debug %(Rule #{matched_rule.name} is selected to make a sampling decision.')
process_matched_rule(matched_rule, now)
else
logger.warn %(No effective centralized sampling rule match. Fallback to local rules.)
@local_sampler.sample_request?(sampling_req)
end
end | ruby | def sample_request?(sampling_req)
start unless @started
now = Time.now.to_i
if sampling_req.nil?
sampling_req = { service_type: @origin } if @origin
elsif !sampling_req.key?(:service_type)
sampling_req[:service_type] = @origin if @origin
end
matched_rule = @cache.get_matched_rule(sampling_req, now: now)
if !matched_rule.nil?
logger.debug %(Rule #{matched_rule.name} is selected to make a sampling decision.')
process_matched_rule(matched_rule, now)
else
logger.warn %(No effective centralized sampling rule match. Fallback to local rules.)
@local_sampler.sample_request?(sampling_req)
end
end | [
"def",
"sample_request?",
"(",
"sampling_req",
")",
"start",
"unless",
"@started",
"now",
"=",
"Time",
".",
"now",
".",
"to_i",
"if",
"sampling_req",
".",
"nil?",
"sampling_req",
"=",
"{",
"service_type",
":",
"@origin",
"}",
"if",
"@origin",
"elsif",
"!",
"sampling_req",
".",
"key?",
"(",
":service_type",
")",
"sampling_req",
"[",
":service_type",
"]",
"=",
"@origin",
"if",
"@origin",
"end",
"matched_rule",
"=",
"@cache",
".",
"get_matched_rule",
"(",
"sampling_req",
",",
"now",
":",
"now",
")",
"if",
"!",
"matched_rule",
".",
"nil?",
"logger",
".",
"debug",
"%(Rule #{matched_rule.name} is selected to make a sampling decision.')",
"process_matched_rule",
"(",
"matched_rule",
",",
"now",
")",
"else",
"logger",
".",
"warn",
"%(No effective centralized sampling rule match. Fallback to local rules.)",
"@local_sampler",
".",
"sample_request?",
"(",
"sampling_req",
")",
"end",
"end"
] | Return the rule name if it decides to sample based on
a service sampling rule matching. If there is no match
it will fallback to local defined sampling rules. | [
"Return",
"the",
"rule",
"name",
"if",
"it",
"decides",
"to",
"sample",
"based",
"on",
"a",
"service",
"sampling",
"rule",
"matching",
".",
"If",
"there",
"is",
"no",
"match",
"it",
"will",
"fallback",
"to",
"local",
"defined",
"sampling",
"rules",
"."
] | 5134f203a0a0c7681e137aa6045ad64fc645c8fe | https://github.com/aws/aws-xray-sdk-ruby/blob/5134f203a0a0c7681e137aa6045ad64fc645c8fe/lib/aws-xray-sdk/sampling/default_sampler.rb#L42-L59 | train |
bigcommerce/bigcommerce-api-ruby | lib/bigcommerce/request.rb | Bigcommerce.PathBuilder.build | def build(keys = [])
keys = [] if keys.nil?
keys = [keys] if keys.is_a? Numeric
ids = uri.scan('%d').count + uri.scan('%s').count
str = ids > keys.size ? uri.chomp('%d').chomp('%s').chomp('/') : uri
(str % keys).chomp('/')
end | ruby | def build(keys = [])
keys = [] if keys.nil?
keys = [keys] if keys.is_a? Numeric
ids = uri.scan('%d').count + uri.scan('%s').count
str = ids > keys.size ? uri.chomp('%d').chomp('%s').chomp('/') : uri
(str % keys).chomp('/')
end | [
"def",
"build",
"(",
"keys",
"=",
"[",
"]",
")",
"keys",
"=",
"[",
"]",
"if",
"keys",
".",
"nil?",
"keys",
"=",
"[",
"keys",
"]",
"if",
"keys",
".",
"is_a?",
"Numeric",
"ids",
"=",
"uri",
".",
"scan",
"(",
"'%d'",
")",
".",
"count",
"+",
"uri",
".",
"scan",
"(",
"'%s'",
")",
".",
"count",
"str",
"=",
"ids",
">",
"keys",
".",
"size",
"?",
"uri",
".",
"chomp",
"(",
"'%d'",
")",
".",
"chomp",
"(",
"'%s'",
")",
".",
"chomp",
"(",
"'/'",
")",
":",
"uri",
"(",
"str",
"%",
"keys",
")",
".",
"chomp",
"(",
"'/'",
")",
"end"
] | This takes the @uri and inserts the keys to form a path.
To start we make sure that for nil/numeric values, we wrap those into an
array. We then scan the string for %d and %s to find the number of times
we possibly need to insert keys into the URI. Next, we check the size of
the keys array, if the keys size is less than the number of possible keys
in the URI, we will remove the trailing %d or %s, then remove the
trailing /. We then pass the keys into the uri to form the path.
ex. foo/%d/bar/%d => foo/1/bar/2 | [
"This",
"takes",
"the"
] | f2f885a324041cfea1fef99077b58dfaa0ad9264 | https://github.com/bigcommerce/bigcommerce-api-ruby/blob/f2f885a324041cfea1fef99077b58dfaa0ad9264/lib/bigcommerce/request.rb#L19-L25 | train |
bigcommerce/bigcommerce-api-ruby | lib/bigcommerce/resources/customers/customer.rb | Bigcommerce.Customer.login_token | def login_token(config: Bigcommerce.config)
payload = {
'iss' => config.client_id,
'iat' => Time.now.to_i,
'jti' => SecureRandom.uuid,
'operation' => 'customer_login',
'store_hash' => config.store_hash,
'customer_id' => id
}
JWT.encode(payload, config.client_secret, 'HS256')
end | ruby | def login_token(config: Bigcommerce.config)
payload = {
'iss' => config.client_id,
'iat' => Time.now.to_i,
'jti' => SecureRandom.uuid,
'operation' => 'customer_login',
'store_hash' => config.store_hash,
'customer_id' => id
}
JWT.encode(payload, config.client_secret, 'HS256')
end | [
"def",
"login_token",
"(",
"config",
":",
"Bigcommerce",
".",
"config",
")",
"payload",
"=",
"{",
"'iss'",
"=>",
"config",
".",
"client_id",
",",
"'iat'",
"=>",
"Time",
".",
"now",
".",
"to_i",
",",
"'jti'",
"=>",
"SecureRandom",
".",
"uuid",
",",
"'operation'",
"=>",
"'customer_login'",
",",
"'store_hash'",
"=>",
"config",
".",
"store_hash",
",",
"'customer_id'",
"=>",
"id",
"}",
"JWT",
".",
"encode",
"(",
"payload",
",",
"config",
".",
"client_secret",
",",
"'HS256'",
")",
"end"
] | Generate a token that can be used to log the customer into the storefront.
This requires your app to have the store_v2_customers_login scope and to
be installed in the store. | [
"Generate",
"a",
"token",
"that",
"can",
"be",
"used",
"to",
"log",
"the",
"customer",
"into",
"the",
"storefront",
".",
"This",
"requires",
"your",
"app",
"to",
"have",
"the",
"store_v2_customers_login",
"scope",
"and",
"to",
"be",
"installed",
"in",
"the",
"store",
"."
] | f2f885a324041cfea1fef99077b58dfaa0ad9264 | https://github.com/bigcommerce/bigcommerce-api-ruby/blob/f2f885a324041cfea1fef99077b58dfaa0ad9264/lib/bigcommerce/resources/customers/customer.rb#L37-L48 | train |
searls/jasmine-rails | lib/jasmine_rails/offline_asset_paths.rb | JasmineRails.OfflineAssetPaths.compute_public_path | def compute_public_path(source, dir, options={})
JasmineRails::OfflineAssetPaths.disabled ? super : compute_asset_path(source, options)
end | ruby | def compute_public_path(source, dir, options={})
JasmineRails::OfflineAssetPaths.disabled ? super : compute_asset_path(source, options)
end | [
"def",
"compute_public_path",
"(",
"source",
",",
"dir",
",",
"options",
"=",
"{",
"}",
")",
"JasmineRails",
"::",
"OfflineAssetPaths",
".",
"disabled",
"?",
"super",
":",
"compute_asset_path",
"(",
"source",
",",
"options",
")",
"end"
] | For Rails 3.2 support | [
"For",
"Rails",
"3",
".",
"2",
"support"
] | 4f0a61d2be4f5156dfa7ab9722276e0184494a75 | https://github.com/searls/jasmine-rails/blob/4f0a61d2be4f5156dfa7ab9722276e0184494a75/lib/jasmine_rails/offline_asset_paths.rb#L30-L32 | train |
searls/jasmine-rails | lib/jasmine_rails/save_fixture.rb | JasmineRails.SaveFixture.save_fixture | def save_fixture(file_name, content = rendered)
fixture_path = File.join(Rails.root, FIXTURE_DIRECTORY, file_name)
fixture_directory = File.dirname(fixture_path)
FileUtils.mkdir_p fixture_directory unless File.exists?(fixture_directory)
File.open(fixture_path, 'w') do |file|
file.puts(content)
end
ignore_generated_fixtures
end | ruby | def save_fixture(file_name, content = rendered)
fixture_path = File.join(Rails.root, FIXTURE_DIRECTORY, file_name)
fixture_directory = File.dirname(fixture_path)
FileUtils.mkdir_p fixture_directory unless File.exists?(fixture_directory)
File.open(fixture_path, 'w') do |file|
file.puts(content)
end
ignore_generated_fixtures
end | [
"def",
"save_fixture",
"(",
"file_name",
",",
"content",
"=",
"rendered",
")",
"fixture_path",
"=",
"File",
".",
"join",
"(",
"Rails",
".",
"root",
",",
"FIXTURE_DIRECTORY",
",",
"file_name",
")",
"fixture_directory",
"=",
"File",
".",
"dirname",
"(",
"fixture_path",
")",
"FileUtils",
".",
"mkdir_p",
"fixture_directory",
"unless",
"File",
".",
"exists?",
"(",
"fixture_directory",
")",
"File",
".",
"open",
"(",
"fixture_path",
",",
"'w'",
")",
"do",
"|",
"file",
"|",
"file",
".",
"puts",
"(",
"content",
")",
"end",
"ignore_generated_fixtures",
"end"
] | Saves the rendered as a fixture file. | [
"Saves",
"the",
"rendered",
"as",
"a",
"fixture",
"file",
"."
] | 4f0a61d2be4f5156dfa7ab9722276e0184494a75 | https://github.com/searls/jasmine-rails/blob/4f0a61d2be4f5156dfa7ab9722276e0184494a75/lib/jasmine_rails/save_fixture.rb#L22-L32 | train |
mattbrictson/airbrussh | lib/airbrussh/console.rb | Airbrussh.Console.print_line | def print_line(obj="")
string = obj.to_s
string = truncate_to_console_width(string) if console_width
string = strip_ascii_color(string) unless color_enabled?
write(string + "\n")
output.flush
end | ruby | def print_line(obj="")
string = obj.to_s
string = truncate_to_console_width(string) if console_width
string = strip_ascii_color(string) unless color_enabled?
write(string + "\n")
output.flush
end | [
"def",
"print_line",
"(",
"obj",
"=",
"\"\"",
")",
"string",
"=",
"obj",
".",
"to_s",
"string",
"=",
"truncate_to_console_width",
"(",
"string",
")",
"if",
"console_width",
"string",
"=",
"strip_ascii_color",
"(",
"string",
")",
"unless",
"color_enabled?",
"write",
"(",
"string",
"+",
"\"\\n\"",
")",
"output",
".",
"flush",
"end"
] | Writes to the IO after first truncating the output to fit the console
width. If the underlying IO is not a TTY, ANSI colors are removed from
the output. A newline is always added. Color output can be forced by
setting the SSHKIT_COLOR environment variable. | [
"Writes",
"to",
"the",
"IO",
"after",
"first",
"truncating",
"the",
"output",
"to",
"fit",
"the",
"console",
"width",
".",
"If",
"the",
"underlying",
"IO",
"is",
"not",
"a",
"TTY",
"ANSI",
"colors",
"are",
"removed",
"from",
"the",
"output",
".",
"A",
"newline",
"is",
"always",
"added",
".",
"Color",
"output",
"can",
"be",
"forced",
"by",
"setting",
"the",
"SSHKIT_COLOR",
"environment",
"variable",
"."
] | eac9bbe3fbf0990cf655746c36a9ba4e1c47950d | https://github.com/mattbrictson/airbrussh/blob/eac9bbe3fbf0990cf655746c36a9ba4e1c47950d/lib/airbrussh/console.rb#L24-L32 | train |
codegram/spinach | lib/spinach/runner.rb | Spinach.Runner.init_reporters | def init_reporters
Spinach.config[:reporter_classes].each do |reporter_class|
reporter_options = default_reporter_options.merge(Spinach.config.reporter_options)
reporter = Support.constantize(reporter_class).new(reporter_options)
reporter.bind
end
end | ruby | def init_reporters
Spinach.config[:reporter_classes].each do |reporter_class|
reporter_options = default_reporter_options.merge(Spinach.config.reporter_options)
reporter = Support.constantize(reporter_class).new(reporter_options)
reporter.bind
end
end | [
"def",
"init_reporters",
"Spinach",
".",
"config",
"[",
":reporter_classes",
"]",
".",
"each",
"do",
"|",
"reporter_class",
"|",
"reporter_options",
"=",
"default_reporter_options",
".",
"merge",
"(",
"Spinach",
".",
"config",
".",
"reporter_options",
")",
"reporter",
"=",
"Support",
".",
"constantize",
"(",
"reporter_class",
")",
".",
"new",
"(",
"reporter_options",
")",
"reporter",
".",
"bind",
"end",
"end"
] | Initializes the runner with a parsed feature
@param [Array<String>] filenames
A list of feature filenames to run
@param [Hash] options
@option options [String] :step_definitions_path
The path in which step definitions are found.
@option options [String] :support_path
The path with the support ruby files.
@api public
Inits the reporter with a default one.
@api public | [
"Initializes",
"the",
"runner",
"with",
"a",
"parsed",
"feature"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/runner.rb#L43-L50 | train |
codegram/spinach | lib/spinach/runner.rb | Spinach.Runner.run | def run
require_dependencies
require_frameworks
init_reporters
suite_passed = true
Spinach.hooks.run_before_run
features_to_run.each do |feature|
feature_passed = FeatureRunner.new(feature, orderer: orderer).run
suite_passed &&= feature_passed
break if fail_fast? && !feature_passed
end
Spinach.hooks.run_after_run(suite_passed)
suite_passed
end | ruby | def run
require_dependencies
require_frameworks
init_reporters
suite_passed = true
Spinach.hooks.run_before_run
features_to_run.each do |feature|
feature_passed = FeatureRunner.new(feature, orderer: orderer).run
suite_passed &&= feature_passed
break if fail_fast? && !feature_passed
end
Spinach.hooks.run_after_run(suite_passed)
suite_passed
end | [
"def",
"run",
"require_dependencies",
"require_frameworks",
"init_reporters",
"suite_passed",
"=",
"true",
"Spinach",
".",
"hooks",
".",
"run_before_run",
"features_to_run",
".",
"each",
"do",
"|",
"feature",
"|",
"feature_passed",
"=",
"FeatureRunner",
".",
"new",
"(",
"feature",
",",
"orderer",
":",
"orderer",
")",
".",
"run",
"suite_passed",
"&&=",
"feature_passed",
"break",
"if",
"fail_fast?",
"&&",
"!",
"feature_passed",
"end",
"Spinach",
".",
"hooks",
".",
"run_after_run",
"(",
"suite_passed",
")",
"suite_passed",
"end"
] | Runs this runner and outputs the results in a colorful manner.
@return [true, false]
Whether the run was succesful.
@api public | [
"Runs",
"this",
"runner",
"and",
"outputs",
"the",
"results",
"in",
"a",
"colorful",
"manner",
"."
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/runner.rb#L58-L77 | train |
codegram/spinach | lib/spinach/runner.rb | Spinach.Runner.orderer | def orderer
@orderer ||= Support.constantize(Spinach.config[:orderer_class]).new(
seed: Spinach.config.seed
)
end | ruby | def orderer
@orderer ||= Support.constantize(Spinach.config[:orderer_class]).new(
seed: Spinach.config.seed
)
end | [
"def",
"orderer",
"@orderer",
"||=",
"Support",
".",
"constantize",
"(",
"Spinach",
".",
"config",
"[",
":orderer_class",
"]",
")",
".",
"new",
"(",
"seed",
":",
"Spinach",
".",
"config",
".",
"seed",
")",
"end"
] | The orderer for this run.
@api public | [
"The",
"orderer",
"for",
"this",
"run",
"."
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/runner.rb#L135-L139 | train |
codegram/spinach | lib/spinach/config.rb | Spinach.Config.parse_from_file | def parse_from_file
parsed_opts = YAML.load_file(config_path)
parsed_opts.delete_if{|k| k.to_s == 'config_path'}
parsed_opts.each_pair{|k,v| self[k] = v}
true
rescue Errno::ENOENT
false
end | ruby | def parse_from_file
parsed_opts = YAML.load_file(config_path)
parsed_opts.delete_if{|k| k.to_s == 'config_path'}
parsed_opts.each_pair{|k,v| self[k] = v}
true
rescue Errno::ENOENT
false
end | [
"def",
"parse_from_file",
"parsed_opts",
"=",
"YAML",
".",
"load_file",
"(",
"config_path",
")",
"parsed_opts",
".",
"delete_if",
"{",
"|",
"k",
"|",
"k",
".",
"to_s",
"==",
"'config_path'",
"}",
"parsed_opts",
".",
"each_pair",
"{",
"|",
"k",
",",
"v",
"|",
"self",
"[",
"k",
"]",
"=",
"v",
"}",
"true",
"rescue",
"Errno",
"::",
"ENOENT",
"false",
"end"
] | Parse options from the config file
@return [Boolean]
If the config was parsed from the file | [
"Parse",
"options",
"from",
"the",
"config",
"file"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/config.rb#L213-L220 | train |
codegram/spinach | lib/spinach/hooks.rb | Spinach.Hooks.on_tag | def on_tag(tag)
before_scenario do |scenario, step_definitions|
tags = scenario.tags
next unless tags.any?
yield(scenario, step_definitions) if tags.include? tag.to_s
end
end | ruby | def on_tag(tag)
before_scenario do |scenario, step_definitions|
tags = scenario.tags
next unless tags.any?
yield(scenario, step_definitions) if tags.include? tag.to_s
end
end | [
"def",
"on_tag",
"(",
"tag",
")",
"before_scenario",
"do",
"|",
"scenario",
",",
"step_definitions",
"|",
"tags",
"=",
"scenario",
".",
"tags",
"next",
"unless",
"tags",
".",
"any?",
"yield",
"(",
"scenario",
",",
"step_definitions",
")",
"if",
"tags",
".",
"include?",
"tag",
".",
"to_s",
"end",
"end"
] | Runs before running a scenario with a particular tag
@param [String] tag
the tag to match
@example
Spinach.hooks.on_tag('javascript') do
# change capybara driver
end | [
"Runs",
"before",
"running",
"a",
"scenario",
"with",
"a",
"particular",
"tag"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/hooks.rb#L168-L174 | train |
codegram/spinach | lib/spinach/auditor.rb | Spinach.Auditor.get_feature_and_defs | def get_feature_and_defs(file)
feature = Parser.open_file(file).parse
[feature, Spinach.find_step_definitions(feature.name)]
end | ruby | def get_feature_and_defs(file)
feature = Parser.open_file(file).parse
[feature, Spinach.find_step_definitions(feature.name)]
end | [
"def",
"get_feature_and_defs",
"(",
"file",
")",
"feature",
"=",
"Parser",
".",
"open_file",
"(",
"file",
")",
".",
"parse",
"[",
"feature",
",",
"Spinach",
".",
"find_step_definitions",
"(",
"feature",
".",
"name",
")",
"]",
"end"
] | Get the feature and its definitions from the appropriate files | [
"Get",
"the",
"feature",
"and",
"its",
"definitions",
"from",
"the",
"appropriate",
"files"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/auditor.rb#L70-L73 | train |
codegram/spinach | lib/spinach/auditor.rb | Spinach.Auditor.step_missing? | def step_missing?(step, step_defs)
method_name = Spinach::Support.underscore step.name
return true unless step_defs.respond_to?(method_name)
# Remember that we have used this step
used_steps << step_defs.step_location_for(step.name).join(':')
false
end | ruby | def step_missing?(step, step_defs)
method_name = Spinach::Support.underscore step.name
return true unless step_defs.respond_to?(method_name)
# Remember that we have used this step
used_steps << step_defs.step_location_for(step.name).join(':')
false
end | [
"def",
"step_missing?",
"(",
"step",
",",
"step_defs",
")",
"method_name",
"=",
"Spinach",
"::",
"Support",
".",
"underscore",
"step",
".",
"name",
"return",
"true",
"unless",
"step_defs",
".",
"respond_to?",
"(",
"method_name",
")",
"# Remember that we have used this step",
"used_steps",
"<<",
"step_defs",
".",
"step_location_for",
"(",
"step",
".",
"name",
")",
".",
"join",
"(",
"':'",
")",
"false",
"end"
] | Process a step from the feature file using the given step_defs.
If it is missing, return true. Otherwise, add it to the used_steps for
the report at the end and return false. | [
"Process",
"a",
"step",
"from",
"the",
"feature",
"file",
"using",
"the",
"given",
"step_defs",
".",
"If",
"it",
"is",
"missing",
"return",
"true",
".",
"Otherwise",
"add",
"it",
"to",
"the",
"used_steps",
"for",
"the",
"report",
"at",
"the",
"end",
"and",
"return",
"false",
"."
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/auditor.rb#L78-L84 | train |
codegram/spinach | lib/spinach/auditor.rb | Spinach.Auditor.store_unused_steps | def store_unused_steps(names, step_defs)
names.each do |name|
location = step_defs.step_location_for(name).join(':')
unused_steps[location] = name
end
end | ruby | def store_unused_steps(names, step_defs)
names.each do |name|
location = step_defs.step_location_for(name).join(':')
unused_steps[location] = name
end
end | [
"def",
"store_unused_steps",
"(",
"names",
",",
"step_defs",
")",
"names",
".",
"each",
"do",
"|",
"name",
"|",
"location",
"=",
"step_defs",
".",
"step_location_for",
"(",
"name",
")",
".",
"join",
"(",
"':'",
")",
"unused_steps",
"[",
"location",
"]",
"=",
"name",
"end",
"end"
] | Store any unused step names for the report at the end of the audit | [
"Store",
"any",
"unused",
"step",
"names",
"for",
"the",
"report",
"at",
"the",
"end",
"of",
"the",
"audit"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/auditor.rb#L87-L92 | train |
codegram/spinach | lib/spinach/auditor.rb | Spinach.Auditor.step_names_for_class | def step_names_for_class(klass)
klass.ancestors.map { |a| a.respond_to?(:steps) ? a.steps : [] }.flatten
end | ruby | def step_names_for_class(klass)
klass.ancestors.map { |a| a.respond_to?(:steps) ? a.steps : [] }.flatten
end | [
"def",
"step_names_for_class",
"(",
"klass",
")",
"klass",
".",
"ancestors",
".",
"map",
"{",
"|",
"a",
"|",
"a",
".",
"respond_to?",
"(",
":steps",
")",
"?",
"a",
".",
"steps",
":",
"[",
"]",
"}",
".",
"flatten",
"end"
] | Get the step names for all steps in the given class, including those in
common modules | [
"Get",
"the",
"step",
"names",
"for",
"all",
"steps",
"in",
"the",
"given",
"class",
"including",
"those",
"in",
"common",
"modules"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/auditor.rb#L104-L106 | train |
codegram/spinach | lib/spinach/auditor.rb | Spinach.Auditor.report_unused_steps | def report_unused_steps
# Remove any unused_steps that were in common modules and used
# in another feature
used_steps.each { |location| unused_steps.delete location }
unused_steps.each do |location, name|
puts "\n" + "Unused step: #{location} ".colorize(:yellow) +
"'#{name}'".colorize(:light_yellow)
end
end | ruby | def report_unused_steps
# Remove any unused_steps that were in common modules and used
# in another feature
used_steps.each { |location| unused_steps.delete location }
unused_steps.each do |location, name|
puts "\n" + "Unused step: #{location} ".colorize(:yellow) +
"'#{name}'".colorize(:light_yellow)
end
end | [
"def",
"report_unused_steps",
"# Remove any unused_steps that were in common modules and used",
"# in another feature",
"used_steps",
".",
"each",
"{",
"|",
"location",
"|",
"unused_steps",
".",
"delete",
"location",
"}",
"unused_steps",
".",
"each",
"do",
"|",
"location",
",",
"name",
"|",
"puts",
"\"\\n\"",
"+",
"\"Unused step: #{location} \"",
".",
"colorize",
"(",
":yellow",
")",
"+",
"\"'#{name}'\"",
".",
"colorize",
"(",
":light_yellow",
")",
"end",
"end"
] | Produce a report of unused steps that were not found anywhere in the audit | [
"Produce",
"a",
"report",
"of",
"unused",
"steps",
"that",
"were",
"not",
"found",
"anywhere",
"in",
"the",
"audit"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/auditor.rb#L109-L117 | train |
codegram/spinach | lib/spinach/auditor.rb | Spinach.Auditor.report_missing_steps | def report_missing_steps(steps)
puts "\nMissing steps:".colorize(:light_cyan)
steps.each do |step|
puts Generators::StepGenerator.new(step).generate.gsub(/^/, ' ')
.colorize(:cyan)
end
end | ruby | def report_missing_steps(steps)
puts "\nMissing steps:".colorize(:light_cyan)
steps.each do |step|
puts Generators::StepGenerator.new(step).generate.gsub(/^/, ' ')
.colorize(:cyan)
end
end | [
"def",
"report_missing_steps",
"(",
"steps",
")",
"puts",
"\"\\nMissing steps:\"",
".",
"colorize",
"(",
":light_cyan",
")",
"steps",
".",
"each",
"do",
"|",
"step",
"|",
"puts",
"Generators",
"::",
"StepGenerator",
".",
"new",
"(",
"step",
")",
".",
"generate",
".",
"gsub",
"(",
"/",
"/",
",",
"' '",
")",
".",
"colorize",
"(",
":cyan",
")",
"end",
"end"
] | Print a report of the missing step objects provided | [
"Print",
"a",
"report",
"of",
"the",
"missing",
"step",
"objects",
"provided"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/auditor.rb#L120-L126 | train |
codegram/spinach | lib/spinach/reporter.rb | Spinach.Reporter.bind | def bind
Spinach.hooks.tap do |hooks|
hooks.before_run { |*args| before_run(*args) }
hooks.after_run { |*args| after_run(*args) }
hooks.before_feature { |*args| before_feature_run(*args) }
hooks.after_feature { |*args| after_feature_run(*args) }
hooks.on_undefined_feature { |*args| on_feature_not_found(*args) }
hooks.before_scenario { |*args| before_scenario_run(*args) }
hooks.around_scenario { |*args, &block| around_scenario_run(*args, &block) }
hooks.after_scenario { |*args| after_scenario_run(*args) }
hooks.on_successful_step { |*args| on_successful_step(*args) }
hooks.on_undefined_step { |*args| on_undefined_step(*args) }
hooks.on_pending_step { |*args| on_pending_step(*args) }
hooks.on_failed_step { |*args| on_failed_step(*args) }
hooks.on_error_step { |*args| on_error_step(*args) }
hooks.on_skipped_step { |*args| on_skipped_step(*args) }
hooks.before_feature { |*args| set_current_feature(*args) }
hooks.after_feature { |*args| clear_current_feature(*args) }
hooks.before_scenario { |*args| set_current_scenario(args.first) }
hooks.after_scenario { |*args| clear_current_scenario(args.first) }
end
end | ruby | def bind
Spinach.hooks.tap do |hooks|
hooks.before_run { |*args| before_run(*args) }
hooks.after_run { |*args| after_run(*args) }
hooks.before_feature { |*args| before_feature_run(*args) }
hooks.after_feature { |*args| after_feature_run(*args) }
hooks.on_undefined_feature { |*args| on_feature_not_found(*args) }
hooks.before_scenario { |*args| before_scenario_run(*args) }
hooks.around_scenario { |*args, &block| around_scenario_run(*args, &block) }
hooks.after_scenario { |*args| after_scenario_run(*args) }
hooks.on_successful_step { |*args| on_successful_step(*args) }
hooks.on_undefined_step { |*args| on_undefined_step(*args) }
hooks.on_pending_step { |*args| on_pending_step(*args) }
hooks.on_failed_step { |*args| on_failed_step(*args) }
hooks.on_error_step { |*args| on_error_step(*args) }
hooks.on_skipped_step { |*args| on_skipped_step(*args) }
hooks.before_feature { |*args| set_current_feature(*args) }
hooks.after_feature { |*args| clear_current_feature(*args) }
hooks.before_scenario { |*args| set_current_scenario(args.first) }
hooks.after_scenario { |*args| clear_current_scenario(args.first) }
end
end | [
"def",
"bind",
"Spinach",
".",
"hooks",
".",
"tap",
"do",
"|",
"hooks",
"|",
"hooks",
".",
"before_run",
"{",
"|",
"*",
"args",
"|",
"before_run",
"(",
"args",
")",
"}",
"hooks",
".",
"after_run",
"{",
"|",
"*",
"args",
"|",
"after_run",
"(",
"args",
")",
"}",
"hooks",
".",
"before_feature",
"{",
"|",
"*",
"args",
"|",
"before_feature_run",
"(",
"args",
")",
"}",
"hooks",
".",
"after_feature",
"{",
"|",
"*",
"args",
"|",
"after_feature_run",
"(",
"args",
")",
"}",
"hooks",
".",
"on_undefined_feature",
"{",
"|",
"*",
"args",
"|",
"on_feature_not_found",
"(",
"args",
")",
"}",
"hooks",
".",
"before_scenario",
"{",
"|",
"*",
"args",
"|",
"before_scenario_run",
"(",
"args",
")",
"}",
"hooks",
".",
"around_scenario",
"{",
"|",
"*",
"args",
",",
"&",
"block",
"|",
"around_scenario_run",
"(",
"args",
",",
"block",
")",
"}",
"hooks",
".",
"after_scenario",
"{",
"|",
"*",
"args",
"|",
"after_scenario_run",
"(",
"args",
")",
"}",
"hooks",
".",
"on_successful_step",
"{",
"|",
"*",
"args",
"|",
"on_successful_step",
"(",
"args",
")",
"}",
"hooks",
".",
"on_undefined_step",
"{",
"|",
"*",
"args",
"|",
"on_undefined_step",
"(",
"args",
")",
"}",
"hooks",
".",
"on_pending_step",
"{",
"|",
"*",
"args",
"|",
"on_pending_step",
"(",
"args",
")",
"}",
"hooks",
".",
"on_failed_step",
"{",
"|",
"*",
"args",
"|",
"on_failed_step",
"(",
"args",
")",
"}",
"hooks",
".",
"on_error_step",
"{",
"|",
"*",
"args",
"|",
"on_error_step",
"(",
"args",
")",
"}",
"hooks",
".",
"on_skipped_step",
"{",
"|",
"*",
"args",
"|",
"on_skipped_step",
"(",
"args",
")",
"}",
"hooks",
".",
"before_feature",
"{",
"|",
"*",
"args",
"|",
"set_current_feature",
"(",
"args",
")",
"}",
"hooks",
".",
"after_feature",
"{",
"|",
"*",
"args",
"|",
"clear_current_feature",
"(",
"args",
")",
"}",
"hooks",
".",
"before_scenario",
"{",
"|",
"*",
"args",
"|",
"set_current_scenario",
"(",
"args",
".",
"first",
")",
"}",
"hooks",
".",
"after_scenario",
"{",
"|",
"*",
"args",
"|",
"clear_current_scenario",
"(",
"args",
".",
"first",
")",
"}",
"end",
"end"
] | Hooks the reporter to the runner endpoints | [
"Hooks",
"the",
"reporter",
"to",
"the",
"runner",
"endpoints"
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/reporter.rb#L29-L51 | train |
codegram/spinach | lib/spinach/cli.rb | Spinach.Cli.feature_files | def feature_files
files_to_run = []
@args.each do |arg|
if arg.match(/\.feature/)
if File.exists? arg.gsub(/:\d*/, '')
files_to_run << arg
else
fail! "#{arg} could not be found"
end
elsif File.directory?(arg)
files_to_run << Dir.glob(File.join(arg, '**', '*.feature'))
elsif arg != "{}"
fail! "invalid argument - #{arg}"
end
end
if !files_to_run.empty?
files_to_run.flatten
else
Dir.glob(File.join(Spinach.config[:features_path], '**', '*.feature'))
end
end | ruby | def feature_files
files_to_run = []
@args.each do |arg|
if arg.match(/\.feature/)
if File.exists? arg.gsub(/:\d*/, '')
files_to_run << arg
else
fail! "#{arg} could not be found"
end
elsif File.directory?(arg)
files_to_run << Dir.glob(File.join(arg, '**', '*.feature'))
elsif arg != "{}"
fail! "invalid argument - #{arg}"
end
end
if !files_to_run.empty?
files_to_run.flatten
else
Dir.glob(File.join(Spinach.config[:features_path], '**', '*.feature'))
end
end | [
"def",
"feature_files",
"files_to_run",
"=",
"[",
"]",
"@args",
".",
"each",
"do",
"|",
"arg",
"|",
"if",
"arg",
".",
"match",
"(",
"/",
"\\.",
"/",
")",
"if",
"File",
".",
"exists?",
"arg",
".",
"gsub",
"(",
"/",
"\\d",
"/",
",",
"''",
")",
"files_to_run",
"<<",
"arg",
"else",
"fail!",
"\"#{arg} could not be found\"",
"end",
"elsif",
"File",
".",
"directory?",
"(",
"arg",
")",
"files_to_run",
"<<",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"arg",
",",
"'**'",
",",
"'*.feature'",
")",
")",
"elsif",
"arg",
"!=",
"\"{}\"",
"fail!",
"\"invalid argument - #{arg}\"",
"end",
"end",
"if",
"!",
"files_to_run",
".",
"empty?",
"files_to_run",
".",
"flatten",
"else",
"Dir",
".",
"glob",
"(",
"File",
".",
"join",
"(",
"Spinach",
".",
"config",
"[",
":features_path",
"]",
",",
"'**'",
",",
"'*.feature'",
")",
")",
"end",
"end"
] | Uses given args to list the feature files to run. It will find a single
feature, features in a folder and subfolders or every feature file in the
feature path.
@return [Array]
An array with the feature file names.
@api public | [
"Uses",
"given",
"args",
"to",
"list",
"the",
"feature",
"files",
"to",
"run",
".",
"It",
"will",
"find",
"a",
"single",
"feature",
"features",
"in",
"a",
"folder",
"and",
"subfolders",
"or",
"every",
"feature",
"file",
"in",
"the",
"feature",
"path",
"."
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/cli.rb#L54-L76 | train |
codegram/spinach | lib/spinach/cli.rb | Spinach.Cli.parse_options | def parse_options
config = {}
begin
OptionParser.new do |opts|
opts.on('-c', '--config_path PATH',
'Parse options from file (will get overriden by flags)') do |file|
Spinach.config[:config_path] = file
end
opts.on('-b', '--backtrace',
'Show backtrace of errors') do |show_backtrace|
config[:reporter_options] = {backtrace: show_backtrace}
end
opts.on('-t', '--tags TAG',
'Run all scenarios for given tags.') do |tag|
config[:tags] ||= []
tags = tag.delete('@').split(',')
if (config[:tags] + tags).flatten.none? { |t| t =~ /wip$/ }
tags.unshift '~wip'
end
config[:tags] << tags
end
opts.on('-g', '--generate',
'Auto-generate the feature steps files') do
config[:generate] = true
end
opts.on_tail('--version', 'Show version') do
puts Spinach::VERSION
exit
end
opts.on('-f', '--features_path PATH',
'Path where your features will be searched for') do |path|
config[:features_path] = path
end
opts.on('-r', '--reporter CLASS_NAMES',
'Formatter class names, separated by commas') do |class_names|
names = class_names.split(',').map { |c| reporter_class(c) }
config[:reporter_classes] = names
end
opts.on('--rand', "Randomize the order of features and scenarios") do
config[:orderer_class] = orderer_class(:random)
end
opts.on('--seed SEED', Integer,
"Provide a seed for randomizing the order of features and scenarios") do |seed|
config[:orderer_class] = orderer_class(:random)
config[:seed] = seed
end
opts.on_tail('--fail-fast',
'Terminate the suite run on the first failure') do |class_name|
config[:fail_fast] = true
end
opts.on('-a', '--audit',
"Audit steps instead of running them, outputting missing \
and obsolete steps") do
config[:audit] = true
end
end.parse!(@args)
Spinach.config.parse_from_file
config.each{|k,v| Spinach.config[k] = v}
if Spinach.config.tags.empty? ||
Spinach.config.tags.flatten.none?{ |t| t =~ /wip$/ }
Spinach.config.tags.unshift ['~wip']
end
rescue OptionParser::ParseError => exception
puts exception.message.capitalize
exit 1
end
end | ruby | def parse_options
config = {}
begin
OptionParser.new do |opts|
opts.on('-c', '--config_path PATH',
'Parse options from file (will get overriden by flags)') do |file|
Spinach.config[:config_path] = file
end
opts.on('-b', '--backtrace',
'Show backtrace of errors') do |show_backtrace|
config[:reporter_options] = {backtrace: show_backtrace}
end
opts.on('-t', '--tags TAG',
'Run all scenarios for given tags.') do |tag|
config[:tags] ||= []
tags = tag.delete('@').split(',')
if (config[:tags] + tags).flatten.none? { |t| t =~ /wip$/ }
tags.unshift '~wip'
end
config[:tags] << tags
end
opts.on('-g', '--generate',
'Auto-generate the feature steps files') do
config[:generate] = true
end
opts.on_tail('--version', 'Show version') do
puts Spinach::VERSION
exit
end
opts.on('-f', '--features_path PATH',
'Path where your features will be searched for') do |path|
config[:features_path] = path
end
opts.on('-r', '--reporter CLASS_NAMES',
'Formatter class names, separated by commas') do |class_names|
names = class_names.split(',').map { |c| reporter_class(c) }
config[:reporter_classes] = names
end
opts.on('--rand', "Randomize the order of features and scenarios") do
config[:orderer_class] = orderer_class(:random)
end
opts.on('--seed SEED', Integer,
"Provide a seed for randomizing the order of features and scenarios") do |seed|
config[:orderer_class] = orderer_class(:random)
config[:seed] = seed
end
opts.on_tail('--fail-fast',
'Terminate the suite run on the first failure') do |class_name|
config[:fail_fast] = true
end
opts.on('-a', '--audit',
"Audit steps instead of running them, outputting missing \
and obsolete steps") do
config[:audit] = true
end
end.parse!(@args)
Spinach.config.parse_from_file
config.each{|k,v| Spinach.config[k] = v}
if Spinach.config.tags.empty? ||
Spinach.config.tags.flatten.none?{ |t| t =~ /wip$/ }
Spinach.config.tags.unshift ['~wip']
end
rescue OptionParser::ParseError => exception
puts exception.message.capitalize
exit 1
end
end | [
"def",
"parse_options",
"config",
"=",
"{",
"}",
"begin",
"OptionParser",
".",
"new",
"do",
"|",
"opts",
"|",
"opts",
".",
"on",
"(",
"'-c'",
",",
"'--config_path PATH'",
",",
"'Parse options from file (will get overriden by flags)'",
")",
"do",
"|",
"file",
"|",
"Spinach",
".",
"config",
"[",
":config_path",
"]",
"=",
"file",
"end",
"opts",
".",
"on",
"(",
"'-b'",
",",
"'--backtrace'",
",",
"'Show backtrace of errors'",
")",
"do",
"|",
"show_backtrace",
"|",
"config",
"[",
":reporter_options",
"]",
"=",
"{",
"backtrace",
":",
"show_backtrace",
"}",
"end",
"opts",
".",
"on",
"(",
"'-t'",
",",
"'--tags TAG'",
",",
"'Run all scenarios for given tags.'",
")",
"do",
"|",
"tag",
"|",
"config",
"[",
":tags",
"]",
"||=",
"[",
"]",
"tags",
"=",
"tag",
".",
"delete",
"(",
"'@'",
")",
".",
"split",
"(",
"','",
")",
"if",
"(",
"config",
"[",
":tags",
"]",
"+",
"tags",
")",
".",
"flatten",
".",
"none?",
"{",
"|",
"t",
"|",
"t",
"=~",
"/",
"/",
"}",
"tags",
".",
"unshift",
"'~wip'",
"end",
"config",
"[",
":tags",
"]",
"<<",
"tags",
"end",
"opts",
".",
"on",
"(",
"'-g'",
",",
"'--generate'",
",",
"'Auto-generate the feature steps files'",
")",
"do",
"config",
"[",
":generate",
"]",
"=",
"true",
"end",
"opts",
".",
"on_tail",
"(",
"'--version'",
",",
"'Show version'",
")",
"do",
"puts",
"Spinach",
"::",
"VERSION",
"exit",
"end",
"opts",
".",
"on",
"(",
"'-f'",
",",
"'--features_path PATH'",
",",
"'Path where your features will be searched for'",
")",
"do",
"|",
"path",
"|",
"config",
"[",
":features_path",
"]",
"=",
"path",
"end",
"opts",
".",
"on",
"(",
"'-r'",
",",
"'--reporter CLASS_NAMES'",
",",
"'Formatter class names, separated by commas'",
")",
"do",
"|",
"class_names",
"|",
"names",
"=",
"class_names",
".",
"split",
"(",
"','",
")",
".",
"map",
"{",
"|",
"c",
"|",
"reporter_class",
"(",
"c",
")",
"}",
"config",
"[",
":reporter_classes",
"]",
"=",
"names",
"end",
"opts",
".",
"on",
"(",
"'--rand'",
",",
"\"Randomize the order of features and scenarios\"",
")",
"do",
"config",
"[",
":orderer_class",
"]",
"=",
"orderer_class",
"(",
":random",
")",
"end",
"opts",
".",
"on",
"(",
"'--seed SEED'",
",",
"Integer",
",",
"\"Provide a seed for randomizing the order of features and scenarios\"",
")",
"do",
"|",
"seed",
"|",
"config",
"[",
":orderer_class",
"]",
"=",
"orderer_class",
"(",
":random",
")",
"config",
"[",
":seed",
"]",
"=",
"seed",
"end",
"opts",
".",
"on_tail",
"(",
"'--fail-fast'",
",",
"'Terminate the suite run on the first failure'",
")",
"do",
"|",
"class_name",
"|",
"config",
"[",
":fail_fast",
"]",
"=",
"true",
"end",
"opts",
".",
"on",
"(",
"'-a'",
",",
"'--audit'",
",",
"\"Audit steps instead of running them, outputting missing \\\nand obsolete steps\"",
")",
"do",
"config",
"[",
":audit",
"]",
"=",
"true",
"end",
"end",
".",
"parse!",
"(",
"@args",
")",
"Spinach",
".",
"config",
".",
"parse_from_file",
"config",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"Spinach",
".",
"config",
"[",
"k",
"]",
"=",
"v",
"}",
"if",
"Spinach",
".",
"config",
".",
"tags",
".",
"empty?",
"||",
"Spinach",
".",
"config",
".",
"tags",
".",
"flatten",
".",
"none?",
"{",
"|",
"t",
"|",
"t",
"=~",
"/",
"/",
"}",
"Spinach",
".",
"config",
".",
"tags",
".",
"unshift",
"[",
"'~wip'",
"]",
"end",
"rescue",
"OptionParser",
"::",
"ParseError",
"=>",
"exception",
"puts",
"exception",
".",
"message",
".",
"capitalize",
"exit",
"1",
"end",
"end"
] | Parses the arguments into options.
@return [Hash]
A hash of options separated by its type.
@api private | [
"Parses",
"the",
"arguments",
"into",
"options",
"."
] | 09ba608a2e9eccad0f0c92ace33aa550a199014a | https://github.com/codegram/spinach/blob/09ba608a2e9eccad0f0c92ace33aa550a199014a/lib/spinach/cli.rb#L86-L166 | train |
matschaffer/knife-solo | lib/knife-solo/ssh_command.rb | KnifeSolo.SshCommand.run_with_fallbacks | def run_with_fallbacks(commands, options = {})
commands.each do |command|
result = run_command(command, options)
return result if result.success?
end
SshConnection::ExecResult.new(1)
end | ruby | def run_with_fallbacks(commands, options = {})
commands.each do |command|
result = run_command(command, options)
return result if result.success?
end
SshConnection::ExecResult.new(1)
end | [
"def",
"run_with_fallbacks",
"(",
"commands",
",",
"options",
"=",
"{",
"}",
")",
"commands",
".",
"each",
"do",
"|",
"command",
"|",
"result",
"=",
"run_command",
"(",
"command",
",",
"options",
")",
"return",
"result",
"if",
"result",
".",
"success?",
"end",
"SshConnection",
"::",
"ExecResult",
".",
"new",
"(",
"1",
")",
"end"
] | Runs commands from the specified array until successful.
Returns the result of the successful command or an ExecResult with
exit_code 1 if all fail. | [
"Runs",
"commands",
"from",
"the",
"specified",
"array",
"until",
"successful",
".",
"Returns",
"the",
"result",
"of",
"the",
"successful",
"command",
"or",
"an",
"ExecResult",
"with",
"exit_code",
"1",
"if",
"all",
"fail",
"."
] | ce8c2237af961394059351260471f6ef417967ba | https://github.com/matschaffer/knife-solo/blob/ce8c2237af961394059351260471f6ef417967ba/lib/knife-solo/ssh_command.rb#L310-L316 | train |
neo4jrb/neo4j-core | lib/neo4j/transaction.rb | Neo4j.Transaction.run | def run(*args)
session, run_in_tx = session_and_run_in_tx_from_args(args)
fail ArgumentError, 'Expected a block to run in Transaction.run' unless block_given?
return yield(nil) unless run_in_tx
tx = Neo4j::Transaction.new(session)
yield tx
rescue Exception => e # rubocop:disable Lint/RescueException
# print_exception_cause(e)
tx.mark_failed unless tx.nil?
raise e
ensure
tx.close unless tx.nil?
end | ruby | def run(*args)
session, run_in_tx = session_and_run_in_tx_from_args(args)
fail ArgumentError, 'Expected a block to run in Transaction.run' unless block_given?
return yield(nil) unless run_in_tx
tx = Neo4j::Transaction.new(session)
yield tx
rescue Exception => e # rubocop:disable Lint/RescueException
# print_exception_cause(e)
tx.mark_failed unless tx.nil?
raise e
ensure
tx.close unless tx.nil?
end | [
"def",
"run",
"(",
"*",
"args",
")",
"session",
",",
"run_in_tx",
"=",
"session_and_run_in_tx_from_args",
"(",
"args",
")",
"fail",
"ArgumentError",
",",
"'Expected a block to run in Transaction.run'",
"unless",
"block_given?",
"return",
"yield",
"(",
"nil",
")",
"unless",
"run_in_tx",
"tx",
"=",
"Neo4j",
"::",
"Transaction",
".",
"new",
"(",
"session",
")",
"yield",
"tx",
"rescue",
"Exception",
"=>",
"e",
"# rubocop:disable Lint/RescueException",
"# print_exception_cause(e)",
"tx",
".",
"mark_failed",
"unless",
"tx",
".",
"nil?",
"raise",
"e",
"ensure",
"tx",
".",
"close",
"unless",
"tx",
".",
"nil?",
"end"
] | Runs the given block in a new transaction.
@param [Boolean] run_in_tx if true a new transaction will not be created, instead if will simply yield to the given block
@@yield [Neo4j::Transaction::Instance] | [
"Runs",
"the",
"given",
"block",
"in",
"a",
"new",
"transaction",
"."
] | 293eb02cc11210e88bfa69d778f563e61f2b0de7 | https://github.com/neo4jrb/neo4j-core/blob/293eb02cc11210e88bfa69d778f563e61f2b0de7/lib/neo4j/transaction.rb#L127-L143 | train |
neo4jrb/neo4j-core | lib/neo4j/transaction.rb | Neo4j.Transaction.session_and_run_in_tx_from_args | def session_and_run_in_tx_from_args(args)
fail ArgumentError, 'Too few arguments' if args.empty?
fail ArgumentError, 'Too many arguments' if args.size > 2
if args.size == 1
fail ArgumentError, 'Session must be specified' if !args[0].is_a?(Neo4j::Core::CypherSession)
[args[0], true]
else
[true, false].include?(args[0]) ? args.reverse : args.dup
end
end | ruby | def session_and_run_in_tx_from_args(args)
fail ArgumentError, 'Too few arguments' if args.empty?
fail ArgumentError, 'Too many arguments' if args.size > 2
if args.size == 1
fail ArgumentError, 'Session must be specified' if !args[0].is_a?(Neo4j::Core::CypherSession)
[args[0], true]
else
[true, false].include?(args[0]) ? args.reverse : args.dup
end
end | [
"def",
"session_and_run_in_tx_from_args",
"(",
"args",
")",
"fail",
"ArgumentError",
",",
"'Too few arguments'",
"if",
"args",
".",
"empty?",
"fail",
"ArgumentError",
",",
"'Too many arguments'",
"if",
"args",
".",
"size",
">",
"2",
"if",
"args",
".",
"size",
"==",
"1",
"fail",
"ArgumentError",
",",
"'Session must be specified'",
"if",
"!",
"args",
"[",
"0",
"]",
".",
"is_a?",
"(",
"Neo4j",
"::",
"Core",
"::",
"CypherSession",
")",
"[",
"args",
"[",
"0",
"]",
",",
"true",
"]",
"else",
"[",
"true",
",",
"false",
"]",
".",
"include?",
"(",
"args",
"[",
"0",
"]",
")",
"?",
"args",
".",
"reverse",
":",
"args",
".",
"dup",
"end",
"end"
] | To support old syntax of providing run_in_tx first
But session first is ideal | [
"To",
"support",
"old",
"syntax",
"of",
"providing",
"run_in_tx",
"first",
"But",
"session",
"first",
"is",
"ideal"
] | 293eb02cc11210e88bfa69d778f563e61f2b0de7 | https://github.com/neo4jrb/neo4j-core/blob/293eb02cc11210e88bfa69d778f563e61f2b0de7/lib/neo4j/transaction.rb#L147-L158 | train |
datamapper/dm-core | lib/dm-core/support/ordered_set.rb | DataMapper.OrderedSet.<< | def <<(entry)
if index = @cache[entry]
entries[index] = entry
else
@cache[entry] = size
entries << entry
end
self
end | ruby | def <<(entry)
if index = @cache[entry]
entries[index] = entry
else
@cache[entry] = size
entries << entry
end
self
end | [
"def",
"<<",
"(",
"entry",
")",
"if",
"index",
"=",
"@cache",
"[",
"entry",
"]",
"entries",
"[",
"index",
"]",
"=",
"entry",
"else",
"@cache",
"[",
"entry",
"]",
"=",
"size",
"entries",
"<<",
"entry",
"end",
"self",
"end"
] | Add or update an entry in the set
If the entry to add isn't part of the set already,
it will be added. If an entry with the same cache
key as the entry to add is part of the set already,
it will be replaced with the given entry.
@param [Object] entry
the entry to be added
@return [OrderedSet] self
@api private | [
"Add",
"or",
"update",
"an",
"entry",
"in",
"the",
"set"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/support/ordered_set.rb#L258-L266 | train |
datamapper/dm-core | lib/dm-core/property_set.rb | DataMapper.PropertySet.[]= | def []=(name, entry)
warn "#{self.class}#[]= is deprecated. Use #{self.class}#<< instead: #{caller.first}"
raise "#{entry.class} is not added with the correct name" unless name && name.to_s == entry.name.to_s
self << entry
entry
end | ruby | def []=(name, entry)
warn "#{self.class}#[]= is deprecated. Use #{self.class}#<< instead: #{caller.first}"
raise "#{entry.class} is not added with the correct name" unless name && name.to_s == entry.name.to_s
self << entry
entry
end | [
"def",
"[]=",
"(",
"name",
",",
"entry",
")",
"warn",
"\"#{self.class}#[]= is deprecated. Use #{self.class}#<< instead: #{caller.first}\"",
"raise",
"\"#{entry.class} is not added with the correct name\"",
"unless",
"name",
"&&",
"name",
".",
"to_s",
"==",
"entry",
".",
"name",
".",
"to_s",
"self",
"<<",
"entry",
"entry",
"end"
] | Make sure that entry is part of this PropertySet
@param [#to_s] name
@param [#name] entry
@return [#name]
the entry that is now part of this PropertySet
@api semipublic | [
"Make",
"sure",
"that",
"entry",
"is",
"part",
"of",
"this",
"PropertySet"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/property_set.rb#L23-L28 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.update | def update(other)
other_options = if kind_of?(other.class)
return self if self.eql?(other)
assert_valid_other(other)
other.options
else
other = other.to_hash
return self if other.empty?
other
end
@options = @options.merge(other_options).freeze
assert_valid_options(@options)
normalize = DataMapper::Ext::Hash.only(other_options, *OPTIONS - [ :conditions ]).map do |attribute, value|
instance_variable_set("@#{attribute}", DataMapper::Ext.try_dup(value))
attribute
end
merge_conditions([ DataMapper::Ext::Hash.except(other_options, *OPTIONS), other_options[:conditions] ])
normalize_options(normalize | [ :links, :unique ])
self
end | ruby | def update(other)
other_options = if kind_of?(other.class)
return self if self.eql?(other)
assert_valid_other(other)
other.options
else
other = other.to_hash
return self if other.empty?
other
end
@options = @options.merge(other_options).freeze
assert_valid_options(@options)
normalize = DataMapper::Ext::Hash.only(other_options, *OPTIONS - [ :conditions ]).map do |attribute, value|
instance_variable_set("@#{attribute}", DataMapper::Ext.try_dup(value))
attribute
end
merge_conditions([ DataMapper::Ext::Hash.except(other_options, *OPTIONS), other_options[:conditions] ])
normalize_options(normalize | [ :links, :unique ])
self
end | [
"def",
"update",
"(",
"other",
")",
"other_options",
"=",
"if",
"kind_of?",
"(",
"other",
".",
"class",
")",
"return",
"self",
"if",
"self",
".",
"eql?",
"(",
"other",
")",
"assert_valid_other",
"(",
"other",
")",
"other",
".",
"options",
"else",
"other",
"=",
"other",
".",
"to_hash",
"return",
"self",
"if",
"other",
".",
"empty?",
"other",
"end",
"@options",
"=",
"@options",
".",
"merge",
"(",
"other_options",
")",
".",
"freeze",
"assert_valid_options",
"(",
"@options",
")",
"normalize",
"=",
"DataMapper",
"::",
"Ext",
"::",
"Hash",
".",
"only",
"(",
"other_options",
",",
"OPTIONS",
"-",
"[",
":conditions",
"]",
")",
".",
"map",
"do",
"|",
"attribute",
",",
"value",
"|",
"instance_variable_set",
"(",
"\"@#{attribute}\"",
",",
"DataMapper",
"::",
"Ext",
".",
"try_dup",
"(",
"value",
")",
")",
"attribute",
"end",
"merge_conditions",
"(",
"[",
"DataMapper",
"::",
"Ext",
"::",
"Hash",
".",
"except",
"(",
"other_options",
",",
"OPTIONS",
")",
",",
"other_options",
"[",
":conditions",
"]",
"]",
")",
"normalize_options",
"(",
"normalize",
"|",
"[",
":links",
",",
":unique",
"]",
")",
"self",
"end"
] | Updates the Query with another Query or conditions
Pretty unrealistic example:
@example
Journal.all(:limit => 2).query.limit # => 2
Journal.all(:limit => 2).query.update(:limit => 3).limit # => 3
@param [Query, Hash] other
other Query or conditions
@return [Query]
self
@api semipublic | [
"Updates",
"the",
"Query",
"with",
"another",
"Query",
"or",
"conditions"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L351-L374 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.filter_records | def filter_records(records)
records = records.uniq if unique?
records = match_records(records) if conditions
records = sort_records(records) if order
records = limit_records(records) if limit || offset > 0
records
end | ruby | def filter_records(records)
records = records.uniq if unique?
records = match_records(records) if conditions
records = sort_records(records) if order
records = limit_records(records) if limit || offset > 0
records
end | [
"def",
"filter_records",
"(",
"records",
")",
"records",
"=",
"records",
".",
"uniq",
"if",
"unique?",
"records",
"=",
"match_records",
"(",
"records",
")",
"if",
"conditions",
"records",
"=",
"sort_records",
"(",
"records",
")",
"if",
"order",
"records",
"=",
"limit_records",
"(",
"records",
")",
"if",
"limit",
"||",
"offset",
">",
"0",
"records",
"end"
] | Takes an Enumerable of records, and destructively filters it.
First finds all matching conditions, then sorts it,
then does offset & limit
@param [Enumerable] records
The set of records to be filtered
@return [Enumerable]
Whats left of the given array after the filtering
@api semipublic | [
"Takes",
"an",
"Enumerable",
"of",
"records",
"and",
"destructively",
"filters",
"it",
".",
"First",
"finds",
"all",
"matching",
"conditions",
"then",
"sorts",
"it",
"then",
"does",
"offset",
"&",
"limit"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L488-L494 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.match_records | def match_records(records)
conditions = self.conditions
records.select { |record| conditions.matches?(record) }
end | ruby | def match_records(records)
conditions = self.conditions
records.select { |record| conditions.matches?(record) }
end | [
"def",
"match_records",
"(",
"records",
")",
"conditions",
"=",
"self",
".",
"conditions",
"records",
".",
"select",
"{",
"|",
"record",
"|",
"conditions",
".",
"matches?",
"(",
"record",
")",
"}",
"end"
] | Filter a set of records by the conditions
@param [Enumerable] records
The set of records to be filtered
@return [Enumerable]
Whats left of the given array after the matching
@api semipublic | [
"Filter",
"a",
"set",
"of",
"records",
"by",
"the",
"conditions"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L505-L508 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.sort_records | def sort_records(records)
sort_order = order.map { |direction| [ direction.target, direction.operator == :asc ] }
records.sort_by do |record|
sort_order.map do |(property, ascending)|
Sort.new(record_value(record, property), ascending)
end
end
end | ruby | def sort_records(records)
sort_order = order.map { |direction| [ direction.target, direction.operator == :asc ] }
records.sort_by do |record|
sort_order.map do |(property, ascending)|
Sort.new(record_value(record, property), ascending)
end
end
end | [
"def",
"sort_records",
"(",
"records",
")",
"sort_order",
"=",
"order",
".",
"map",
"{",
"|",
"direction",
"|",
"[",
"direction",
".",
"target",
",",
"direction",
".",
"operator",
"==",
":asc",
"]",
"}",
"records",
".",
"sort_by",
"do",
"|",
"record",
"|",
"sort_order",
".",
"map",
"do",
"|",
"(",
"property",
",",
"ascending",
")",
"|",
"Sort",
".",
"new",
"(",
"record_value",
"(",
"record",
",",
"property",
")",
",",
"ascending",
")",
"end",
"end",
"end"
] | Sorts a list of Records by the order
@param [Enumerable] records
A list of Resources to sort
@return [Enumerable]
The sorted records
@api semipublic | [
"Sorts",
"a",
"list",
"of",
"Records",
"by",
"the",
"order"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L519-L527 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.slice! | def slice!(*args)
offset, limit = extract_slice_arguments(*args)
if self.limit || self.offset > 0
offset, limit = get_relative_position(offset, limit)
end
update(:offset => offset, :limit => limit)
end | ruby | def slice!(*args)
offset, limit = extract_slice_arguments(*args)
if self.limit || self.offset > 0
offset, limit = get_relative_position(offset, limit)
end
update(:offset => offset, :limit => limit)
end | [
"def",
"slice!",
"(",
"*",
"args",
")",
"offset",
",",
"limit",
"=",
"extract_slice_arguments",
"(",
"args",
")",
"if",
"self",
".",
"limit",
"||",
"self",
".",
"offset",
">",
"0",
"offset",
",",
"limit",
"=",
"get_relative_position",
"(",
"offset",
",",
"limit",
")",
"end",
"update",
"(",
":offset",
"=>",
"offset",
",",
":limit",
"=>",
"limit",
")",
"end"
] | Slices collection by adding limit and offset to the
query, so a single query is executed
@example
Journal.all(:limit => 10).slice!(3, 5)
will execute query with the following limit
(when repository uses DataObjects adapter, and thus
queries use SQL):
LIMIT 10
and then takes a slice of collection in the Ruby space
@api semipublic | [
"Slices",
"collection",
"by",
"adding",
"limit",
"and",
"offset",
"to",
"the",
"query",
"so",
"a",
"single",
"query",
"is",
"executed"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L588-L596 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.inspect | def inspect
attrs = [
[ :repository, repository.name ],
[ :model, model ],
[ :fields, fields ],
[ :links, links ],
[ :conditions, conditions ],
[ :order, order ],
[ :limit, limit ],
[ :offset, offset ],
[ :reload, reload? ],
[ :unique, unique? ],
]
"#<#{self.class.name} #{attrs.map { |key, value| "@#{key}=#{value.inspect}" }.join(' ')}>"
end | ruby | def inspect
attrs = [
[ :repository, repository.name ],
[ :model, model ],
[ :fields, fields ],
[ :links, links ],
[ :conditions, conditions ],
[ :order, order ],
[ :limit, limit ],
[ :offset, offset ],
[ :reload, reload? ],
[ :unique, unique? ],
]
"#<#{self.class.name} #{attrs.map { |key, value| "@#{key}=#{value.inspect}" }.join(' ')}>"
end | [
"def",
"inspect",
"attrs",
"=",
"[",
"[",
":repository",
",",
"repository",
".",
"name",
"]",
",",
"[",
":model",
",",
"model",
"]",
",",
"[",
":fields",
",",
"fields",
"]",
",",
"[",
":links",
",",
"links",
"]",
",",
"[",
":conditions",
",",
"conditions",
"]",
",",
"[",
":order",
",",
"order",
"]",
",",
"[",
":limit",
",",
"limit",
"]",
",",
"[",
":offset",
",",
"offset",
"]",
",",
"[",
":reload",
",",
"reload?",
"]",
",",
"[",
":unique",
",",
"unique?",
"]",
",",
"]",
"\"#<#{self.class.name} #{attrs.map { |key, value| \"@#{key}=#{value.inspect}\" }.join(' ')}>\"",
"end"
] | Returns detailed human readable
string representation of the query
@return [String] detailed string representation of the query
@api semipublic | [
"Returns",
"detailed",
"human",
"readable",
"string",
"representation",
"of",
"the",
"query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L604-L619 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.condition_properties | def condition_properties
properties = Set.new
each_comparison do |comparison|
next unless comparison.respond_to?(:subject)
subject = comparison.subject
properties << subject if subject.kind_of?(Property)
end
properties
end | ruby | def condition_properties
properties = Set.new
each_comparison do |comparison|
next unless comparison.respond_to?(:subject)
subject = comparison.subject
properties << subject if subject.kind_of?(Property)
end
properties
end | [
"def",
"condition_properties",
"properties",
"=",
"Set",
".",
"new",
"each_comparison",
"do",
"|",
"comparison",
"|",
"next",
"unless",
"comparison",
".",
"respond_to?",
"(",
":subject",
")",
"subject",
"=",
"comparison",
".",
"subject",
"properties",
"<<",
"subject",
"if",
"subject",
".",
"kind_of?",
"(",
"Property",
")",
"end",
"properties",
"end"
] | Get the properties used in the conditions
@return [Set<Property>]
Set of properties used in the conditions
@api private | [
"Get",
"the",
"properties",
"used",
"in",
"the",
"conditions"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L627-L637 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.to_subquery | def to_subquery
collection = model.all(merge(:fields => model_key))
Conditions::Operation.new(:and, Conditions::Comparison.new(:in, self_relationship, collection))
end | ruby | def to_subquery
collection = model.all(merge(:fields => model_key))
Conditions::Operation.new(:and, Conditions::Comparison.new(:in, self_relationship, collection))
end | [
"def",
"to_subquery",
"collection",
"=",
"model",
".",
"all",
"(",
"merge",
"(",
":fields",
"=>",
"model_key",
")",
")",
"Conditions",
"::",
"Operation",
".",
"new",
"(",
":and",
",",
"Conditions",
"::",
"Comparison",
".",
"new",
"(",
":in",
",",
"self_relationship",
",",
"collection",
")",
")",
"end"
] | Transform Query into subquery conditions
@return [AndOperation]
a subquery for the Query
@api private | [
"Transform",
"Query",
"into",
"subquery",
"conditions"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L655-L658 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.to_hash | def to_hash
{
:repository => repository.name,
:model => model.name,
:fields => fields,
:links => links,
:conditions => conditions,
:offset => offset,
:limit => limit,
:order => order,
:unique => unique?,
:add_reversed => add_reversed?,
:reload => reload?,
}
end | ruby | def to_hash
{
:repository => repository.name,
:model => model.name,
:fields => fields,
:links => links,
:conditions => conditions,
:offset => offset,
:limit => limit,
:order => order,
:unique => unique?,
:add_reversed => add_reversed?,
:reload => reload?,
}
end | [
"def",
"to_hash",
"{",
":repository",
"=>",
"repository",
".",
"name",
",",
":model",
"=>",
"model",
".",
"name",
",",
":fields",
"=>",
"fields",
",",
":links",
"=>",
"links",
",",
":conditions",
"=>",
"conditions",
",",
":offset",
"=>",
"offset",
",",
":limit",
"=>",
"limit",
",",
":order",
"=>",
"order",
",",
":unique",
"=>",
"unique?",
",",
":add_reversed",
"=>",
"add_reversed?",
",",
":reload",
"=>",
"reload?",
",",
"}",
"end"
] | Hash representation of a Query
@return [Hash]
Hash representation of a Query
@api private | [
"Hash",
"representation",
"of",
"a",
"Query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L666-L680 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.assert_valid_options | def assert_valid_options(options)
options = options.to_hash
options.each do |attribute, value|
case attribute
when :fields then assert_valid_fields(value, options[:unique])
when :links then assert_valid_links(value)
when :conditions then assert_valid_conditions(value)
when :offset then assert_valid_offset(value, options[:limit])
when :limit then assert_valid_limit(value)
when :order then assert_valid_order(value, options[:fields])
when :unique, :add_reversed, :reload then assert_valid_boolean("options[:#{attribute}]", value)
else
assert_valid_conditions(attribute => value)
end
end
end | ruby | def assert_valid_options(options)
options = options.to_hash
options.each do |attribute, value|
case attribute
when :fields then assert_valid_fields(value, options[:unique])
when :links then assert_valid_links(value)
when :conditions then assert_valid_conditions(value)
when :offset then assert_valid_offset(value, options[:limit])
when :limit then assert_valid_limit(value)
when :order then assert_valid_order(value, options[:fields])
when :unique, :add_reversed, :reload then assert_valid_boolean("options[:#{attribute}]", value)
else
assert_valid_conditions(attribute => value)
end
end
end | [
"def",
"assert_valid_options",
"(",
"options",
")",
"options",
"=",
"options",
".",
"to_hash",
"options",
".",
"each",
"do",
"|",
"attribute",
",",
"value",
"|",
"case",
"attribute",
"when",
":fields",
"then",
"assert_valid_fields",
"(",
"value",
",",
"options",
"[",
":unique",
"]",
")",
"when",
":links",
"then",
"assert_valid_links",
"(",
"value",
")",
"when",
":conditions",
"then",
"assert_valid_conditions",
"(",
"value",
")",
"when",
":offset",
"then",
"assert_valid_offset",
"(",
"value",
",",
"options",
"[",
":limit",
"]",
")",
"when",
":limit",
"then",
"assert_valid_limit",
"(",
"value",
")",
"when",
":order",
"then",
"assert_valid_order",
"(",
"value",
",",
"options",
"[",
":fields",
"]",
")",
"when",
":unique",
",",
":add_reversed",
",",
":reload",
"then",
"assert_valid_boolean",
"(",
"\"options[:#{attribute}]\"",
",",
"value",
")",
"else",
"assert_valid_conditions",
"(",
"attribute",
"=>",
"value",
")",
"end",
"end",
"end"
] | Validate the options
@param [#each] options
the options to validate
@raise [ArgumentError]
if any pairs in +options+ are invalid options
@api private | [
"Validate",
"the",
"options"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L763-L779 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.assert_valid_offset | def assert_valid_offset(offset, limit)
unless offset >= 0
raise ArgumentError, "+options[:offset]+ must be greater than or equal to 0, but was #{offset.inspect}"
end
if offset > 0 && limit.nil?
raise ArgumentError, '+options[:offset]+ cannot be greater than 0 if limit is not specified'
end
end | ruby | def assert_valid_offset(offset, limit)
unless offset >= 0
raise ArgumentError, "+options[:offset]+ must be greater than or equal to 0, but was #{offset.inspect}"
end
if offset > 0 && limit.nil?
raise ArgumentError, '+options[:offset]+ cannot be greater than 0 if limit is not specified'
end
end | [
"def",
"assert_valid_offset",
"(",
"offset",
",",
"limit",
")",
"unless",
"offset",
">=",
"0",
"raise",
"ArgumentError",
",",
"\"+options[:offset]+ must be greater than or equal to 0, but was #{offset.inspect}\"",
"end",
"if",
"offset",
">",
"0",
"&&",
"limit",
".",
"nil?",
"raise",
"ArgumentError",
",",
"'+options[:offset]+ cannot be greater than 0 if limit is not specified'",
"end",
"end"
] | Verifies that query offset is non-negative and only used together with limit
@api private | [
"Verifies",
"that",
"query",
"offset",
"is",
"non",
"-",
"negative",
"and",
"only",
"used",
"together",
"with",
"limit"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L856-L864 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.assert_valid_other | def assert_valid_other(other)
other_repository = other.repository
repository = self.repository
other_class = other.class
unless other_repository == repository
raise ArgumentError, "+other+ #{other_class} must be for the #{repository.name} repository, not #{other_repository.name}"
end
other_model = other.model
model = self.model
unless other_model >= model
raise ArgumentError, "+other+ #{other_class} must be for the #{model.name} model, not #{other_model.name}"
end
end | ruby | def assert_valid_other(other)
other_repository = other.repository
repository = self.repository
other_class = other.class
unless other_repository == repository
raise ArgumentError, "+other+ #{other_class} must be for the #{repository.name} repository, not #{other_repository.name}"
end
other_model = other.model
model = self.model
unless other_model >= model
raise ArgumentError, "+other+ #{other_class} must be for the #{model.name} model, not #{other_model.name}"
end
end | [
"def",
"assert_valid_other",
"(",
"other",
")",
"other_repository",
"=",
"other",
".",
"repository",
"repository",
"=",
"self",
".",
"repository",
"other_class",
"=",
"other",
".",
"class",
"unless",
"other_repository",
"==",
"repository",
"raise",
"ArgumentError",
",",
"\"+other+ #{other_class} must be for the #{repository.name} repository, not #{other_repository.name}\"",
"end",
"other_model",
"=",
"other",
".",
"model",
"model",
"=",
"self",
".",
"model",
"unless",
"other_model",
">=",
"model",
"raise",
"ArgumentError",
",",
"\"+other+ #{other_class} must be for the #{model.name} model, not #{other_model.name}\"",
"end",
"end"
] | Verifies that associations given in conditions belong
to the same repository as query's model
@api private | [
"Verifies",
"that",
"associations",
"given",
"in",
"conditions",
"belong",
"to",
"the",
"same",
"repository",
"as",
"query",
"s",
"model"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L905-L920 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.merge_conditions | def merge_conditions(conditions)
@conditions = Conditions::Operation.new(:and) << @conditions unless @conditions.nil?
conditions.compact!
conditions.each do |condition|
case condition
when Conditions::AbstractOperation, Conditions::AbstractComparison
add_condition(condition)
when Hash
condition.each { |key, value| append_condition(key, value) }
when Array
statement, *bind_values = *condition
raw_condition = [ statement ]
raw_condition << bind_values if bind_values.size > 0
add_condition(raw_condition)
@raw = true
end
end
end | ruby | def merge_conditions(conditions)
@conditions = Conditions::Operation.new(:and) << @conditions unless @conditions.nil?
conditions.compact!
conditions.each do |condition|
case condition
when Conditions::AbstractOperation, Conditions::AbstractComparison
add_condition(condition)
when Hash
condition.each { |key, value| append_condition(key, value) }
when Array
statement, *bind_values = *condition
raw_condition = [ statement ]
raw_condition << bind_values if bind_values.size > 0
add_condition(raw_condition)
@raw = true
end
end
end | [
"def",
"merge_conditions",
"(",
"conditions",
")",
"@conditions",
"=",
"Conditions",
"::",
"Operation",
".",
"new",
"(",
":and",
")",
"<<",
"@conditions",
"unless",
"@conditions",
".",
"nil?",
"conditions",
".",
"compact!",
"conditions",
".",
"each",
"do",
"|",
"condition",
"|",
"case",
"condition",
"when",
"Conditions",
"::",
"AbstractOperation",
",",
"Conditions",
"::",
"AbstractComparison",
"add_condition",
"(",
"condition",
")",
"when",
"Hash",
"condition",
".",
"each",
"{",
"|",
"key",
",",
"value",
"|",
"append_condition",
"(",
"key",
",",
"value",
")",
"}",
"when",
"Array",
"statement",
",",
"*",
"bind_values",
"=",
"condition",
"raw_condition",
"=",
"[",
"statement",
"]",
"raw_condition",
"<<",
"bind_values",
"if",
"bind_values",
".",
"size",
">",
"0",
"add_condition",
"(",
"raw_condition",
")",
"@raw",
"=",
"true",
"end",
"end",
"end"
] | Handle all the conditions options provided
@param [Array<Conditions::AbstractOperation, Conditions::AbstractComparison, Hash, Array>]
a list of conditions
@return [undefined]
@api private | [
"Handle",
"all",
"the",
"conditions",
"options",
"provided"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L930-L950 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.append_condition | def append_condition(subject, bind_value, model = self.model, operator = :eql)
case subject
when Property, Associations::Relationship then append_property_condition(subject, bind_value, operator)
when Symbol then append_symbol_condition(subject, bind_value, model, operator)
when String then append_string_condition(subject, bind_value, model, operator)
when Operator then append_operator_conditions(subject, bind_value, model)
when Path then append_path(subject, bind_value, model, operator)
else
raise ArgumentError, "#{subject} is an invalid instance: #{subject.class}"
end
end | ruby | def append_condition(subject, bind_value, model = self.model, operator = :eql)
case subject
when Property, Associations::Relationship then append_property_condition(subject, bind_value, operator)
when Symbol then append_symbol_condition(subject, bind_value, model, operator)
when String then append_string_condition(subject, bind_value, model, operator)
when Operator then append_operator_conditions(subject, bind_value, model)
when Path then append_path(subject, bind_value, model, operator)
else
raise ArgumentError, "#{subject} is an invalid instance: #{subject.class}"
end
end | [
"def",
"append_condition",
"(",
"subject",
",",
"bind_value",
",",
"model",
"=",
"self",
".",
"model",
",",
"operator",
"=",
":eql",
")",
"case",
"subject",
"when",
"Property",
",",
"Associations",
"::",
"Relationship",
"then",
"append_property_condition",
"(",
"subject",
",",
"bind_value",
",",
"operator",
")",
"when",
"Symbol",
"then",
"append_symbol_condition",
"(",
"subject",
",",
"bind_value",
",",
"model",
",",
"operator",
")",
"when",
"String",
"then",
"append_string_condition",
"(",
"subject",
",",
"bind_value",
",",
"model",
",",
"operator",
")",
"when",
"Operator",
"then",
"append_operator_conditions",
"(",
"subject",
",",
"bind_value",
",",
"model",
")",
"when",
"Path",
"then",
"append_path",
"(",
"subject",
",",
"bind_value",
",",
"model",
",",
"operator",
")",
"else",
"raise",
"ArgumentError",
",",
"\"#{subject} is an invalid instance: #{subject.class}\"",
"end",
"end"
] | Append conditions to this Query
TODO: needs example
@param [Property, Symbol, String, Operator, Associations::Relationship, Path] subject
the subject to match
@param [Object] bind_value
the value to match on
@param [Symbol] operator
the operator to match with
@return [Query::Conditions::AbstractOperation]
the Query conditions
@api private | [
"Append",
"conditions",
"to",
"this",
"Query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L1068-L1078 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.set_operation | def set_operation(operation, other)
assert_valid_other(other)
query = self.class.new(@repository, @model, other.to_relative_hash)
query.instance_variable_set(:@conditions, other_conditions(other, operation))
query
end | ruby | def set_operation(operation, other)
assert_valid_other(other)
query = self.class.new(@repository, @model, other.to_relative_hash)
query.instance_variable_set(:@conditions, other_conditions(other, operation))
query
end | [
"def",
"set_operation",
"(",
"operation",
",",
"other",
")",
"assert_valid_other",
"(",
"other",
")",
"query",
"=",
"self",
".",
"class",
".",
"new",
"(",
"@repository",
",",
"@model",
",",
"other",
".",
"to_relative_hash",
")",
"query",
".",
"instance_variable_set",
"(",
":@conditions",
",",
"other_conditions",
"(",
"other",
",",
"operation",
")",
")",
"query",
"end"
] | Apply a set operation on self and another query
@param [Symbol] operation
the set operation to apply
@param [Query] other
the other query to apply the set operation on
@return [Query]
the query that was created for the set operation
@api private | [
"Apply",
"a",
"set",
"operation",
"on",
"self",
"and",
"another",
"query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L1272-L1277 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.other_conditions | def other_conditions(other, operation)
self_conditions = query_conditions(self)
unless self_conditions.kind_of?(Conditions::Operation)
operation_slug = case operation
when :intersection, :difference then :and
when :union then :or
end
self_conditions = Conditions::Operation.new(operation_slug, self_conditions)
end
self_conditions.send(operation, query_conditions(other))
end | ruby | def other_conditions(other, operation)
self_conditions = query_conditions(self)
unless self_conditions.kind_of?(Conditions::Operation)
operation_slug = case operation
when :intersection, :difference then :and
when :union then :or
end
self_conditions = Conditions::Operation.new(operation_slug, self_conditions)
end
self_conditions.send(operation, query_conditions(other))
end | [
"def",
"other_conditions",
"(",
"other",
",",
"operation",
")",
"self_conditions",
"=",
"query_conditions",
"(",
"self",
")",
"unless",
"self_conditions",
".",
"kind_of?",
"(",
"Conditions",
"::",
"Operation",
")",
"operation_slug",
"=",
"case",
"operation",
"when",
":intersection",
",",
":difference",
"then",
":and",
"when",
":union",
"then",
":or",
"end",
"self_conditions",
"=",
"Conditions",
"::",
"Operation",
".",
"new",
"(",
"operation_slug",
",",
"self_conditions",
")",
"end",
"self_conditions",
".",
"send",
"(",
"operation",
",",
"query_conditions",
"(",
"other",
")",
")",
"end"
] | Return the union with another query's conditions
@param [Query] other
the query conditions to union with
@return [OrOperation]
the union of the query conditions and other conditions
@api private | [
"Return",
"the",
"union",
"with",
"another",
"query",
"s",
"conditions"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L1288-L1301 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.query_conditions | def query_conditions(query)
if query.limit || query.links.any?
query.to_subquery
else
query.conditions
end
end | ruby | def query_conditions(query)
if query.limit || query.links.any?
query.to_subquery
else
query.conditions
end
end | [
"def",
"query_conditions",
"(",
"query",
")",
"if",
"query",
".",
"limit",
"||",
"query",
".",
"links",
".",
"any?",
"query",
".",
"to_subquery",
"else",
"query",
".",
"conditions",
"end",
"end"
] | Extract conditions from a Query
@param [Query] query
the query with conditions
@return [AbstractOperation]
the operation
@api private | [
"Extract",
"conditions",
"from",
"a",
"Query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L1312-L1318 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.self_relationship | def self_relationship
@self_relationship ||=
begin
model = self.model
Associations::OneToMany::Relationship.new(
:self,
model,
model,
self_relationship_options
)
end
end | ruby | def self_relationship
@self_relationship ||=
begin
model = self.model
Associations::OneToMany::Relationship.new(
:self,
model,
model,
self_relationship_options
)
end
end | [
"def",
"self_relationship",
"@self_relationship",
"||=",
"begin",
"model",
"=",
"self",
".",
"model",
"Associations",
"::",
"OneToMany",
"::",
"Relationship",
".",
"new",
"(",
":self",
",",
"model",
",",
"model",
",",
"self_relationship_options",
")",
"end",
"end"
] | Return a self referrential relationship
@return [Associations::OneToMany::Relationship]
the 1:m association to the same model
@api private | [
"Return",
"a",
"self",
"referrential",
"relationship"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L1326-L1337 | train |
datamapper/dm-core | lib/dm-core/query.rb | DataMapper.Query.self_relationship_options | def self_relationship_options
keys = model_key.map { |property| property.name }
repository = self.repository
{
:child_key => keys,
:parent_key => keys,
:child_repository_name => repository.name,
:parent_repository_name => repository.name,
}
end | ruby | def self_relationship_options
keys = model_key.map { |property| property.name }
repository = self.repository
{
:child_key => keys,
:parent_key => keys,
:child_repository_name => repository.name,
:parent_repository_name => repository.name,
}
end | [
"def",
"self_relationship_options",
"keys",
"=",
"model_key",
".",
"map",
"{",
"|",
"property",
"|",
"property",
".",
"name",
"}",
"repository",
"=",
"self",
".",
"repository",
"{",
":child_key",
"=>",
"keys",
",",
":parent_key",
"=>",
"keys",
",",
":child_repository_name",
"=>",
"repository",
".",
"name",
",",
":parent_repository_name",
"=>",
"repository",
".",
"name",
",",
"}",
"end"
] | Return options for the self referrential relationship
@return [Hash]
the options to use with the self referrential relationship
@api private | [
"Return",
"options",
"for",
"the",
"self",
"referrential",
"relationship"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/query.rb#L1345-L1354 | train |
datamapper/dm-core | lib/dm-core/model.rb | DataMapper.Model.get | def get(*key)
assert_valid_key_size(key)
repository = self.repository
key = self.key(repository.name).typecast(key)
repository.identity_map(self)[key] || first(key_conditions(repository, key).update(:order => nil))
end | ruby | def get(*key)
assert_valid_key_size(key)
repository = self.repository
key = self.key(repository.name).typecast(key)
repository.identity_map(self)[key] || first(key_conditions(repository, key).update(:order => nil))
end | [
"def",
"get",
"(",
"*",
"key",
")",
"assert_valid_key_size",
"(",
"key",
")",
"repository",
"=",
"self",
".",
"repository",
"key",
"=",
"self",
".",
"key",
"(",
"repository",
".",
"name",
")",
".",
"typecast",
"(",
"key",
")",
"repository",
".",
"identity_map",
"(",
"self",
")",
"[",
"key",
"]",
"||",
"first",
"(",
"key_conditions",
"(",
"repository",
",",
"key",
")",
".",
"update",
"(",
":order",
"=>",
"nil",
")",
")",
"end"
] | Grab a single record by its key. Supports natural and composite key
lookups as well.
Zoo.get(1) # get the zoo with primary key of 1.
Zoo.get!(1) # Or get! if you want an ObjectNotFoundError on failure
Zoo.get('DFW') # wow, support for natural primary keys
Zoo.get('Metro', 'DFW') # more wow, composite key look-up
@param [Object] *key
The primary key or keys to use for lookup
@return [Resource, nil]
A single model that was found
If no instance was found matching +key+
@api public | [
"Grab",
"a",
"single",
"record",
"by",
"its",
"key",
".",
"Supports",
"natural",
"and",
"composite",
"key",
"lookups",
"as",
"well",
"."
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/model.rb#L275-L282 | train |
datamapper/dm-core | lib/dm-core/model.rb | DataMapper.Model.first | def first(*args)
first_arg = args.first
last_arg = args.last
limit_specified = first_arg.kind_of?(Integer)
with_query = (last_arg.kind_of?(Hash) && !last_arg.empty?) || last_arg.kind_of?(Query)
limit = limit_specified ? first_arg : 1
query = with_query ? last_arg : {}
query = self.query.slice(0, limit).update(query)
if limit_specified
all(query)
else
query.repository.read(query).first
end
end | ruby | def first(*args)
first_arg = args.first
last_arg = args.last
limit_specified = first_arg.kind_of?(Integer)
with_query = (last_arg.kind_of?(Hash) && !last_arg.empty?) || last_arg.kind_of?(Query)
limit = limit_specified ? first_arg : 1
query = with_query ? last_arg : {}
query = self.query.slice(0, limit).update(query)
if limit_specified
all(query)
else
query.repository.read(query).first
end
end | [
"def",
"first",
"(",
"*",
"args",
")",
"first_arg",
"=",
"args",
".",
"first",
"last_arg",
"=",
"args",
".",
"last",
"limit_specified",
"=",
"first_arg",
".",
"kind_of?",
"(",
"Integer",
")",
"with_query",
"=",
"(",
"last_arg",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"!",
"last_arg",
".",
"empty?",
")",
"||",
"last_arg",
".",
"kind_of?",
"(",
"Query",
")",
"limit",
"=",
"limit_specified",
"?",
"first_arg",
":",
"1",
"query",
"=",
"with_query",
"?",
"last_arg",
":",
"{",
"}",
"query",
"=",
"self",
".",
"query",
".",
"slice",
"(",
"0",
",",
"limit",
")",
".",
"update",
"(",
"query",
")",
"if",
"limit_specified",
"all",
"(",
"query",
")",
"else",
"query",
".",
"repository",
".",
"read",
"(",
"query",
")",
".",
"first",
"end",
"end"
] | Return the first Resource or the first N Resources for the Model with an optional query
When there are no arguments, return the first Resource in the
Model. When the first argument is an Integer, return a
Collection containing the first N Resources. When the last
(optional) argument is a Hash scope the results to the query.
@param [Integer] limit (optional)
limit the returned Collection to a specific number of entries
@param [Hash] query (optional)
scope the returned Resource or Collection to the supplied query
@return [Resource, Collection]
The first resource in the entries of this collection,
or a new collection whose query has been merged
@api public | [
"Return",
"the",
"first",
"Resource",
"or",
"the",
"first",
"N",
"Resources",
"for",
"the",
"Model",
"with",
"an",
"optional",
"query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/model.rb#L368-L385 | train |
datamapper/dm-core | lib/dm-core/model.rb | DataMapper.Model.copy | def copy(source_repository_name, target_repository_name, query = {})
target_properties = properties(target_repository_name)
query[:fields] ||= properties(source_repository_name).select do |property|
target_properties.include?(property)
end
repository(target_repository_name) do |repository|
resources = []
all(query.merge(:repository => source_repository_name)).each do |resource|
new_resource = new
query[:fields].each { |property| new_resource.__send__("#{property.name}=", property.get(resource)) }
resources << new_resource if new_resource.save
end
all(Query.target_query(repository, self, resources))
end
end | ruby | def copy(source_repository_name, target_repository_name, query = {})
target_properties = properties(target_repository_name)
query[:fields] ||= properties(source_repository_name).select do |property|
target_properties.include?(property)
end
repository(target_repository_name) do |repository|
resources = []
all(query.merge(:repository => source_repository_name)).each do |resource|
new_resource = new
query[:fields].each { |property| new_resource.__send__("#{property.name}=", property.get(resource)) }
resources << new_resource if new_resource.save
end
all(Query.target_query(repository, self, resources))
end
end | [
"def",
"copy",
"(",
"source_repository_name",
",",
"target_repository_name",
",",
"query",
"=",
"{",
"}",
")",
"target_properties",
"=",
"properties",
"(",
"target_repository_name",
")",
"query",
"[",
":fields",
"]",
"||=",
"properties",
"(",
"source_repository_name",
")",
".",
"select",
"do",
"|",
"property",
"|",
"target_properties",
".",
"include?",
"(",
"property",
")",
"end",
"repository",
"(",
"target_repository_name",
")",
"do",
"|",
"repository",
"|",
"resources",
"=",
"[",
"]",
"all",
"(",
"query",
".",
"merge",
"(",
":repository",
"=>",
"source_repository_name",
")",
")",
".",
"each",
"do",
"|",
"resource",
"|",
"new_resource",
"=",
"new",
"query",
"[",
":fields",
"]",
".",
"each",
"{",
"|",
"property",
"|",
"new_resource",
".",
"__send__",
"(",
"\"#{property.name}=\"",
",",
"property",
".",
"get",
"(",
"resource",
")",
")",
"}",
"resources",
"<<",
"new_resource",
"if",
"new_resource",
".",
"save",
"end",
"all",
"(",
"Query",
".",
"target_query",
"(",
"repository",
",",
"self",
",",
"resources",
")",
")",
"end",
"end"
] | Copy a set of records from one repository to another.
@param [String] source_repository_name
The name of the Repository the resources should be copied _from_
@param [String] target_repository_name
The name of the Repository the resources should be copied _to_
@param [Hash] query
The conditions with which to find the records to copy. These
conditions are merged with Model.query
@return [Collection]
A Collection of the Resource instances created in the operation
@api public | [
"Copy",
"a",
"set",
"of",
"records",
"from",
"one",
"repository",
"to",
"another",
"."
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/model.rb#L543-L561 | train |
datamapper/dm-core | lib/dm-core/model.rb | DataMapper.Model.repository_name | def repository_name
context = Repository.context
context.any? ? context.last.name : default_repository_name
end | ruby | def repository_name
context = Repository.context
context.any? ? context.last.name : default_repository_name
end | [
"def",
"repository_name",
"context",
"=",
"Repository",
".",
"context",
"context",
".",
"any?",
"?",
"context",
".",
"last",
".",
"name",
":",
"default_repository_name",
"end"
] | Get the current +repository_name+ for this Model.
If there are any Repository contexts, the name of the last one will
be returned, else the +default_repository_name+ of this model will be
@return [String]
the current repository name to use for this Model
@api private | [
"Get",
"the",
"current",
"+",
"repository_name",
"+",
"for",
"this",
"Model",
"."
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/model.rb#L701-L704 | train |
datamapper/dm-core | lib/dm-core/model.rb | DataMapper.Model.finalize_allowed_writer_methods | def finalize_allowed_writer_methods
@allowed_writer_methods = public_instance_methods.map { |method| method.to_s }.grep(WRITER_METHOD_REGEXP).to_set
@allowed_writer_methods -= INVALID_WRITER_METHODS
@allowed_writer_methods.freeze
end | ruby | def finalize_allowed_writer_methods
@allowed_writer_methods = public_instance_methods.map { |method| method.to_s }.grep(WRITER_METHOD_REGEXP).to_set
@allowed_writer_methods -= INVALID_WRITER_METHODS
@allowed_writer_methods.freeze
end | [
"def",
"finalize_allowed_writer_methods",
"@allowed_writer_methods",
"=",
"public_instance_methods",
".",
"map",
"{",
"|",
"method",
"|",
"method",
".",
"to_s",
"}",
".",
"grep",
"(",
"WRITER_METHOD_REGEXP",
")",
".",
"to_set",
"@allowed_writer_methods",
"-=",
"INVALID_WRITER_METHODS",
"@allowed_writer_methods",
".",
"freeze",
"end"
] | Initialize the list of allowed writer methods
@return [undefined]
@api private | [
"Initialize",
"the",
"list",
"of",
"allowed",
"writer",
"methods"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/model.rb#L796-L800 | train |
datamapper/dm-core | lib/dm-core/model.rb | DataMapper.Model.assert_valid_properties | def assert_valid_properties
repository_name = self.repository_name
if properties(repository_name).empty? &&
!relationships(repository_name).any? { |relationship| relationship.kind_of?(Associations::ManyToOne::Relationship) }
raise IncompleteModelError, "#{name} must have at least one property or many to one relationship in #{repository_name} to be valid"
end
end | ruby | def assert_valid_properties
repository_name = self.repository_name
if properties(repository_name).empty? &&
!relationships(repository_name).any? { |relationship| relationship.kind_of?(Associations::ManyToOne::Relationship) }
raise IncompleteModelError, "#{name} must have at least one property or many to one relationship in #{repository_name} to be valid"
end
end | [
"def",
"assert_valid_properties",
"repository_name",
"=",
"self",
".",
"repository_name",
"if",
"properties",
"(",
"repository_name",
")",
".",
"empty?",
"&&",
"!",
"relationships",
"(",
"repository_name",
")",
".",
"any?",
"{",
"|",
"relationship",
"|",
"relationship",
".",
"kind_of?",
"(",
"Associations",
"::",
"ManyToOne",
"::",
"Relationship",
")",
"}",
"raise",
"IncompleteModelError",
",",
"\"#{name} must have at least one property or many to one relationship in #{repository_name} to be valid\"",
"end",
"end"
] | Test if the model has properties
A model may also be valid if it has at least one m:1 relationships which
will add inferred foreign key properties.
@return [undefined]
@raise [IncompleteModelError]
raised if the model has no properties
@api private | [
"Test",
"if",
"the",
"model",
"has",
"properties"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/model.rb#L852-L858 | train |
datamapper/dm-core | lib/dm-core/support/subject_set.rb | DataMapper.SubjectSet.[] | def [](name)
name = name.to_s
entries.detect { |entry| entry.name.to_s == name }
end | ruby | def [](name)
name = name.to_s
entries.detect { |entry| entry.name.to_s == name }
end | [
"def",
"[]",
"(",
"name",
")",
"name",
"=",
"name",
".",
"to_s",
"entries",
".",
"detect",
"{",
"|",
"entry",
"|",
"entry",
".",
"name",
".",
"to_s",
"==",
"name",
"}",
"end"
] | Lookup an entry in the SubjectSet based on a given name
@param [#to_s] name
the name of the entry
@return [Object, nil]
the entry having the given name, or nil if not found
@api private | [
"Lookup",
"an",
"entry",
"in",
"the",
"SubjectSet",
"based",
"on",
"a",
"given",
"name"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/support/subject_set.rb#L193-L196 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.reload | def reload(other_query = Undefined)
query = self.query
query = other_query.equal?(Undefined) ? query.dup : query.merge(other_query)
# make sure the Identity Map contains all the existing resources
identity_map = repository.identity_map(model)
loaded_entries.each do |resource|
identity_map[resource.key] = resource
end
# sort fields based on declared order, for more consistent reload queries
properties = self.properties
fields = properties & (query.fields | model_key | [ properties.discriminator ].compact)
# replace the list of resources
replace(all(query.update(:fields => fields, :reload => true)))
end | ruby | def reload(other_query = Undefined)
query = self.query
query = other_query.equal?(Undefined) ? query.dup : query.merge(other_query)
# make sure the Identity Map contains all the existing resources
identity_map = repository.identity_map(model)
loaded_entries.each do |resource|
identity_map[resource.key] = resource
end
# sort fields based on declared order, for more consistent reload queries
properties = self.properties
fields = properties & (query.fields | model_key | [ properties.discriminator ].compact)
# replace the list of resources
replace(all(query.update(:fields => fields, :reload => true)))
end | [
"def",
"reload",
"(",
"other_query",
"=",
"Undefined",
")",
"query",
"=",
"self",
".",
"query",
"query",
"=",
"other_query",
".",
"equal?",
"(",
"Undefined",
")",
"?",
"query",
".",
"dup",
":",
"query",
".",
"merge",
"(",
"other_query",
")",
"# make sure the Identity Map contains all the existing resources",
"identity_map",
"=",
"repository",
".",
"identity_map",
"(",
"model",
")",
"loaded_entries",
".",
"each",
"do",
"|",
"resource",
"|",
"identity_map",
"[",
"resource",
".",
"key",
"]",
"=",
"resource",
"end",
"# sort fields based on declared order, for more consistent reload queries",
"properties",
"=",
"self",
".",
"properties",
"fields",
"=",
"properties",
"&",
"(",
"query",
".",
"fields",
"|",
"model_key",
"|",
"[",
"properties",
".",
"discriminator",
"]",
".",
"compact",
")",
"# replace the list of resources",
"replace",
"(",
"all",
"(",
"query",
".",
"update",
"(",
":fields",
"=>",
"fields",
",",
":reload",
"=>",
"true",
")",
")",
")",
"end"
] | Reloads the Collection from the repository
If +query+ is provided, updates this Collection's query with its conditions
cars_from_91 = Cars.all(:year_manufactured => 1991)
cars_from_91.first.year_manufactured = 2001 # note: not saved
cars_from_91.reload
cars_from_91.first.year #=> 1991
@param [Query, Hash] query (optional)
further restrict results with query
@return [self]
@api public | [
"Reloads",
"the",
"Collection",
"from",
"the",
"repository"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L64-L81 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.get | def get(*key)
assert_valid_key_size(key)
key = model_key.typecast(key)
query = self.query
@identity_map[key] || if !loaded? && (query.limit || query.offset > 0)
# current query is exclusive, find resource within the set
# TODO: use a subquery to retrieve the Collection and then match
# it up against the key. This will require some changes to
# how subqueries are generated, since the key may be a
# composite key. In the case of DO adapters, it means subselects
# like the form "(a, b) IN(SELECT a, b FROM ...)", which will
# require making it so the Query condition key can be a
# Property or an Array of Property objects
# use the brute force approach until subquery lookups work
lazy_load
@identity_map[key]
else
# current query is all inclusive, lookup using normal approach
first(model.key_conditions(repository, key).update(:order => nil))
end
end | ruby | def get(*key)
assert_valid_key_size(key)
key = model_key.typecast(key)
query = self.query
@identity_map[key] || if !loaded? && (query.limit || query.offset > 0)
# current query is exclusive, find resource within the set
# TODO: use a subquery to retrieve the Collection and then match
# it up against the key. This will require some changes to
# how subqueries are generated, since the key may be a
# composite key. In the case of DO adapters, it means subselects
# like the form "(a, b) IN(SELECT a, b FROM ...)", which will
# require making it so the Query condition key can be a
# Property or an Array of Property objects
# use the brute force approach until subquery lookups work
lazy_load
@identity_map[key]
else
# current query is all inclusive, lookup using normal approach
first(model.key_conditions(repository, key).update(:order => nil))
end
end | [
"def",
"get",
"(",
"*",
"key",
")",
"assert_valid_key_size",
"(",
"key",
")",
"key",
"=",
"model_key",
".",
"typecast",
"(",
"key",
")",
"query",
"=",
"self",
".",
"query",
"@identity_map",
"[",
"key",
"]",
"||",
"if",
"!",
"loaded?",
"&&",
"(",
"query",
".",
"limit",
"||",
"query",
".",
"offset",
">",
"0",
")",
"# current query is exclusive, find resource within the set",
"# TODO: use a subquery to retrieve the Collection and then match",
"# it up against the key. This will require some changes to",
"# how subqueries are generated, since the key may be a",
"# composite key. In the case of DO adapters, it means subselects",
"# like the form \"(a, b) IN(SELECT a, b FROM ...)\", which will",
"# require making it so the Query condition key can be a",
"# Property or an Array of Property objects",
"# use the brute force approach until subquery lookups work",
"lazy_load",
"@identity_map",
"[",
"key",
"]",
"else",
"# current query is all inclusive, lookup using normal approach",
"first",
"(",
"model",
".",
"key_conditions",
"(",
"repository",
",",
"key",
")",
".",
"update",
"(",
":order",
"=>",
"nil",
")",
")",
"end",
"end"
] | Lookup a Resource in the Collection by key
This looksup a Resource by key, typecasting the key to the
proper object if necessary.
toyotas = Cars.all(:manufacturer => 'Toyota')
toyo = Cars.first(:manufacturer => 'Toyota')
toyotas.get(toyo.id) == toyo #=> true
@param [Enumerable] *key
keys which uniquely identify a resource in the Collection
@return [Resource]
Resource which matches the supplied key
@return [nil]
No Resource matches the supplied key
@api public | [
"Lookup",
"a",
"Resource",
"in",
"the",
"Collection",
"by",
"key"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L147-L171 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.all | def all(query = Undefined)
if query.equal?(Undefined) || (query.kind_of?(Hash) && query.empty?)
dup
else
# TODO: if there is no order parameter, and the Collection is not loaded
# check to see if the query can be satisfied by the head/tail
new_collection(scoped_query(query))
end
end | ruby | def all(query = Undefined)
if query.equal?(Undefined) || (query.kind_of?(Hash) && query.empty?)
dup
else
# TODO: if there is no order parameter, and the Collection is not loaded
# check to see if the query can be satisfied by the head/tail
new_collection(scoped_query(query))
end
end | [
"def",
"all",
"(",
"query",
"=",
"Undefined",
")",
"if",
"query",
".",
"equal?",
"(",
"Undefined",
")",
"||",
"(",
"query",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"query",
".",
"empty?",
")",
"dup",
"else",
"# TODO: if there is no order parameter, and the Collection is not loaded",
"# check to see if the query can be satisfied by the head/tail",
"new_collection",
"(",
"scoped_query",
"(",
"query",
")",
")",
"end",
"end"
] | Returns a new Collection optionally scoped by +query+
This returns a new Collection scoped relative to the current
Collection.
cars_from_91 = Cars.all(:year_manufactured => 1991)
toyotas_91 = cars_from_91.all(:manufacturer => 'Toyota')
toyotas_91.all? { |car| car.year_manufactured == 1991 } #=> true
toyotas_91.all? { |car| car.manufacturer == 'Toyota' } #=> true
If +query+ is a Hash, results will be found by merging +query+ with this Collection's query.
If +query+ is a Query, results will be found using +query+ as an absolute query.
@param [Hash, Query] query
optional parameters to scope results with
@return [Collection]
Collection scoped by +query+
@api public | [
"Returns",
"a",
"new",
"Collection",
"optionally",
"scoped",
"by",
"+",
"query",
"+"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L213-L221 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.first | def first(*args)
first_arg = args.first
last_arg = args.last
limit_specified = first_arg.kind_of?(Integer)
with_query = (last_arg.kind_of?(Hash) && !last_arg.empty?) || last_arg.kind_of?(Query)
limit = limit_specified ? first_arg : 1
query = with_query ? last_arg : {}
query = self.query.slice(0, limit).update(query)
# TODO: when a query provided, and there are enough elements in head to
# satisfy the query.limit, filter the head with the query, and make
# sure it matches the limit exactly. if so, use that result instead
# of calling all()
# - this can probably only be done if there is no :order parameter
loaded = loaded?
head = self.head
collection = if !with_query && (loaded || lazy_possible?(head, limit))
new_collection(query, super(limit))
else
all(query)
end
return collection if limit_specified
resource = collection.to_a.first
if with_query || loaded
resource
elsif resource
head[0] = resource
end
end | ruby | def first(*args)
first_arg = args.first
last_arg = args.last
limit_specified = first_arg.kind_of?(Integer)
with_query = (last_arg.kind_of?(Hash) && !last_arg.empty?) || last_arg.kind_of?(Query)
limit = limit_specified ? first_arg : 1
query = with_query ? last_arg : {}
query = self.query.slice(0, limit).update(query)
# TODO: when a query provided, and there are enough elements in head to
# satisfy the query.limit, filter the head with the query, and make
# sure it matches the limit exactly. if so, use that result instead
# of calling all()
# - this can probably only be done if there is no :order parameter
loaded = loaded?
head = self.head
collection = if !with_query && (loaded || lazy_possible?(head, limit))
new_collection(query, super(limit))
else
all(query)
end
return collection if limit_specified
resource = collection.to_a.first
if with_query || loaded
resource
elsif resource
head[0] = resource
end
end | [
"def",
"first",
"(",
"*",
"args",
")",
"first_arg",
"=",
"args",
".",
"first",
"last_arg",
"=",
"args",
".",
"last",
"limit_specified",
"=",
"first_arg",
".",
"kind_of?",
"(",
"Integer",
")",
"with_query",
"=",
"(",
"last_arg",
".",
"kind_of?",
"(",
"Hash",
")",
"&&",
"!",
"last_arg",
".",
"empty?",
")",
"||",
"last_arg",
".",
"kind_of?",
"(",
"Query",
")",
"limit",
"=",
"limit_specified",
"?",
"first_arg",
":",
"1",
"query",
"=",
"with_query",
"?",
"last_arg",
":",
"{",
"}",
"query",
"=",
"self",
".",
"query",
".",
"slice",
"(",
"0",
",",
"limit",
")",
".",
"update",
"(",
"query",
")",
"# TODO: when a query provided, and there are enough elements in head to",
"# satisfy the query.limit, filter the head with the query, and make",
"# sure it matches the limit exactly. if so, use that result instead",
"# of calling all()",
"# - this can probably only be done if there is no :order parameter",
"loaded",
"=",
"loaded?",
"head",
"=",
"self",
".",
"head",
"collection",
"=",
"if",
"!",
"with_query",
"&&",
"(",
"loaded",
"||",
"lazy_possible?",
"(",
"head",
",",
"limit",
")",
")",
"new_collection",
"(",
"query",
",",
"super",
"(",
"limit",
")",
")",
"else",
"all",
"(",
"query",
")",
"end",
"return",
"collection",
"if",
"limit_specified",
"resource",
"=",
"collection",
".",
"to_a",
".",
"first",
"if",
"with_query",
"||",
"loaded",
"resource",
"elsif",
"resource",
"head",
"[",
"0",
"]",
"=",
"resource",
"end",
"end"
] | Return the first Resource or the first N Resources in the Collection with an optional query
When there are no arguments, return the first Resource in the
Collection. When the first argument is an Integer, return a
Collection containing the first N Resources. When the last
(optional) argument is a Hash scope the results to the query.
@param [Integer] limit (optional)
limit the returned Collection to a specific number of entries
@param [Hash] query (optional)
scope the returned Resource or Collection to the supplied query
@return [Resource, Collection]
The first resource in the entries of this collection,
or a new collection whose query has been merged
@api public | [
"Return",
"the",
"first",
"Resource",
"or",
"the",
"first",
"N",
"Resources",
"in",
"the",
"Collection",
"with",
"an",
"optional",
"query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L240-L276 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.at | def at(offset)
if loaded? || partially_loaded?(offset)
super
elsif offset == 0
first
elsif offset > 0
first(:offset => offset)
elsif offset == -1
last
else
last(:offset => offset.abs - 1)
end
end | ruby | def at(offset)
if loaded? || partially_loaded?(offset)
super
elsif offset == 0
first
elsif offset > 0
first(:offset => offset)
elsif offset == -1
last
else
last(:offset => offset.abs - 1)
end
end | [
"def",
"at",
"(",
"offset",
")",
"if",
"loaded?",
"||",
"partially_loaded?",
"(",
"offset",
")",
"super",
"elsif",
"offset",
"==",
"0",
"first",
"elsif",
"offset",
">",
"0",
"first",
"(",
":offset",
"=>",
"offset",
")",
"elsif",
"offset",
"==",
"-",
"1",
"last",
"else",
"last",
"(",
":offset",
"=>",
"offset",
".",
"abs",
"-",
"1",
")",
"end",
"end"
] | Lookup a Resource from the Collection by offset
@param [Integer] offset
offset of the Resource in the Collection
@return [Resource]
Resource which matches the supplied offset
@return [nil]
No Resource matches the supplied offset
@api public | [
"Lookup",
"a",
"Resource",
"from",
"the",
"Collection",
"by",
"offset"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L346-L358 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.slice! | def slice!(*args)
removed = super
resources_removed(removed) unless removed.nil?
# Workaround for Ruby <= 1.8.6
compact! if RUBY_VERSION <= '1.8.6'
unless removed.kind_of?(Enumerable)
return removed
end
offset, limit = extract_slice_arguments(*args)
query = sliced_query(offset, limit)
new_collection(query, removed)
end | ruby | def slice!(*args)
removed = super
resources_removed(removed) unless removed.nil?
# Workaround for Ruby <= 1.8.6
compact! if RUBY_VERSION <= '1.8.6'
unless removed.kind_of?(Enumerable)
return removed
end
offset, limit = extract_slice_arguments(*args)
query = sliced_query(offset, limit)
new_collection(query, removed)
end | [
"def",
"slice!",
"(",
"*",
"args",
")",
"removed",
"=",
"super",
"resources_removed",
"(",
"removed",
")",
"unless",
"removed",
".",
"nil?",
"# Workaround for Ruby <= 1.8.6",
"compact!",
"if",
"RUBY_VERSION",
"<=",
"'1.8.6'",
"unless",
"removed",
".",
"kind_of?",
"(",
"Enumerable",
")",
"return",
"removed",
"end",
"offset",
",",
"limit",
"=",
"extract_slice_arguments",
"(",
"args",
")",
"query",
"=",
"sliced_query",
"(",
"offset",
",",
"limit",
")",
"new_collection",
"(",
"query",
",",
"removed",
")",
"end"
] | Deletes and Returns the Resources given by an offset or a Range
@param [Integer, Array(Integer), Range] *args
the offset, offset and limit, or range indicating first and last position
@return [Resource, Collection]
The entry which resides at that offset and limit, or
a new Collection object with the set limits and offset
@return [Resource, Collection, nil]
The offset is out of range
@api public | [
"Deletes",
"and",
"Returns",
"the",
"Resources",
"given",
"by",
"an",
"offset",
"or",
"a",
"Range"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L419-L436 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.[]= | def []=(*args)
orphans = Array(superclass_slice(*args[0..-2]))
# relate new resources
resources = resources_added(super)
# mark resources as removed
resources_removed(orphans - loaded_entries)
resources
end | ruby | def []=(*args)
orphans = Array(superclass_slice(*args[0..-2]))
# relate new resources
resources = resources_added(super)
# mark resources as removed
resources_removed(orphans - loaded_entries)
resources
end | [
"def",
"[]=",
"(",
"*",
"args",
")",
"orphans",
"=",
"Array",
"(",
"superclass_slice",
"(",
"args",
"[",
"0",
"..",
"-",
"2",
"]",
")",
")",
"# relate new resources",
"resources",
"=",
"resources_added",
"(",
"super",
")",
"# mark resources as removed",
"resources_removed",
"(",
"orphans",
"-",
"loaded_entries",
")",
"resources",
"end"
] | Splice a list of Resources at a given offset or range
When nil is provided instead of a Resource or a list of Resources
this will remove all of the Resources at the specified position.
@param [Integer, Array(Integer), Range] *args
The offset, offset and limit, or range indicating first and last position.
The last argument may be a Resource, a list of Resources or nil.
@return [Resource, Enumerable]
the Resource or list of Resources that was spliced into the Collection
@return [nil]
If nil was used to delete the entries
@api public | [
"Splice",
"a",
"list",
"of",
"Resources",
"at",
"a",
"given",
"offset",
"or",
"range"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L453-L463 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.each | def each
return to_enum unless block_given?
super do |resource|
begin
original, resource.collection = resource.collection, self
yield resource
ensure
resource.collection = original
end
end
end | ruby | def each
return to_enum unless block_given?
super do |resource|
begin
original, resource.collection = resource.collection, self
yield resource
ensure
resource.collection = original
end
end
end | [
"def",
"each",
"return",
"to_enum",
"unless",
"block_given?",
"super",
"do",
"|",
"resource",
"|",
"begin",
"original",
",",
"resource",
".",
"collection",
"=",
"resource",
".",
"collection",
",",
"self",
"yield",
"resource",
"ensure",
"resource",
".",
"collection",
"=",
"original",
"end",
"end",
"end"
] | Iterate over each Resource
@yield [Resource] Each resource in the collection
@return [self]
@api public | [
"Iterate",
"over",
"each",
"Resource"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L503-L513 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.new | def new(attributes = {})
resource = repository.scope { model.new(attributes) }
self << resource
resource
end | ruby | def new(attributes = {})
resource = repository.scope { model.new(attributes) }
self << resource
resource
end | [
"def",
"new",
"(",
"attributes",
"=",
"{",
"}",
")",
"resource",
"=",
"repository",
".",
"scope",
"{",
"model",
".",
"new",
"(",
"attributes",
")",
"}",
"self",
"<<",
"resource",
"resource",
"end"
] | Initializes a Resource and appends it to the Collection
@param [Hash] attributes
Attributes with which to initialize the new resource
@return [Resource]
a new Resource initialized with +attributes+
@api public | [
"Initializes",
"a",
"Resource",
"and",
"appends",
"it",
"to",
"the",
"Collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L778-L782 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.update | def update(attributes)
assert_update_clean_only(:update)
dirty_attributes = model.new(attributes).dirty_attributes
dirty_attributes.empty? || all? { |resource| resource.update(attributes) }
end | ruby | def update(attributes)
assert_update_clean_only(:update)
dirty_attributes = model.new(attributes).dirty_attributes
dirty_attributes.empty? || all? { |resource| resource.update(attributes) }
end | [
"def",
"update",
"(",
"attributes",
")",
"assert_update_clean_only",
"(",
":update",
")",
"dirty_attributes",
"=",
"model",
".",
"new",
"(",
"attributes",
")",
".",
"dirty_attributes",
"dirty_attributes",
".",
"empty?",
"||",
"all?",
"{",
"|",
"resource",
"|",
"resource",
".",
"update",
"(",
"attributes",
")",
"}",
"end"
] | Update every Resource in the Collection
Person.all(:age.gte => 21).update(:allow_beer => true)
@param [Hash] attributes
attributes to update with
@return [Boolean]
true if the resources were successfully updated
@api public | [
"Update",
"every",
"Resource",
"in",
"the",
"Collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L821-L826 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.update! | def update!(attributes)
assert_update_clean_only(:update!)
model = self.model
dirty_attributes = model.new(attributes).dirty_attributes
if dirty_attributes.empty?
true
else
dirty_attributes.each do |property, value|
property.assert_valid_value(value)
end
unless _update(dirty_attributes)
return false
end
if loaded?
each do |resource|
dirty_attributes.each { |property, value| property.set!(resource, value) }
repository.identity_map(model)[resource.key] = resource
end
end
true
end
end | ruby | def update!(attributes)
assert_update_clean_only(:update!)
model = self.model
dirty_attributes = model.new(attributes).dirty_attributes
if dirty_attributes.empty?
true
else
dirty_attributes.each do |property, value|
property.assert_valid_value(value)
end
unless _update(dirty_attributes)
return false
end
if loaded?
each do |resource|
dirty_attributes.each { |property, value| property.set!(resource, value) }
repository.identity_map(model)[resource.key] = resource
end
end
true
end
end | [
"def",
"update!",
"(",
"attributes",
")",
"assert_update_clean_only",
"(",
":update!",
")",
"model",
"=",
"self",
".",
"model",
"dirty_attributes",
"=",
"model",
".",
"new",
"(",
"attributes",
")",
".",
"dirty_attributes",
"if",
"dirty_attributes",
".",
"empty?",
"true",
"else",
"dirty_attributes",
".",
"each",
"do",
"|",
"property",
",",
"value",
"|",
"property",
".",
"assert_valid_value",
"(",
"value",
")",
"end",
"unless",
"_update",
"(",
"dirty_attributes",
")",
"return",
"false",
"end",
"if",
"loaded?",
"each",
"do",
"|",
"resource",
"|",
"dirty_attributes",
".",
"each",
"{",
"|",
"property",
",",
"value",
"|",
"property",
".",
"set!",
"(",
"resource",
",",
"value",
")",
"}",
"repository",
".",
"identity_map",
"(",
"model",
")",
"[",
"resource",
".",
"key",
"]",
"=",
"resource",
"end",
"end",
"true",
"end",
"end"
] | Update every Resource in the Collection bypassing validation
Person.all(:age.gte => 21).update!(:allow_beer => true)
@param [Hash] attributes
attributes to update
@return [Boolean]
true if the resources were successfully updated
@api public | [
"Update",
"every",
"Resource",
"in",
"the",
"Collection",
"bypassing",
"validation"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L839-L865 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.destroy! | def destroy!
repository = self.repository
deleted = repository.delete(self)
if loaded?
unless deleted == size
return false
end
each do |resource|
resource.persistence_state = Resource::PersistenceState::Immutable.new(resource)
end
clear
else
mark_loaded
end
true
end | ruby | def destroy!
repository = self.repository
deleted = repository.delete(self)
if loaded?
unless deleted == size
return false
end
each do |resource|
resource.persistence_state = Resource::PersistenceState::Immutable.new(resource)
end
clear
else
mark_loaded
end
true
end | [
"def",
"destroy!",
"repository",
"=",
"self",
".",
"repository",
"deleted",
"=",
"repository",
".",
"delete",
"(",
"self",
")",
"if",
"loaded?",
"unless",
"deleted",
"==",
"size",
"return",
"false",
"end",
"each",
"do",
"|",
"resource",
"|",
"resource",
".",
"persistence_state",
"=",
"Resource",
"::",
"PersistenceState",
"::",
"Immutable",
".",
"new",
"(",
"resource",
")",
"end",
"clear",
"else",
"mark_loaded",
"end",
"true",
"end"
] | Remove all Resources from the repository, bypassing validation
This performs a deletion of each Resource in the Collection from
the repository and clears the Collection while skipping
validation.
@return [Boolean]
true if the resources were successfully destroyed
@api public | [
"Remove",
"all",
"Resources",
"from",
"the",
"repository",
"bypassing",
"validation"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L914-L933 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.respond_to? | def respond_to?(method, include_private = false)
super || model.respond_to?(method) || relationships.named?(method)
end | ruby | def respond_to?(method, include_private = false)
super || model.respond_to?(method) || relationships.named?(method)
end | [
"def",
"respond_to?",
"(",
"method",
",",
"include_private",
"=",
"false",
")",
"super",
"||",
"model",
".",
"respond_to?",
"(",
"method",
")",
"||",
"relationships",
".",
"named?",
"(",
"method",
")",
"end"
] | Check to see if collection can respond to the method
@param [Symbol] method
method to check in the object
@param [Boolean] include_private
if set to true, collection will check private methods
@return [Boolean]
true if method can be responded to
@api public | [
"Check",
"to",
"see",
"if",
"collection",
"can",
"respond",
"to",
"the",
"method"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L946-L948 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.partially_loaded? | def partially_loaded?(offset, limit = 1)
if offset >= 0
lazy_possible?(head, offset + limit)
else
lazy_possible?(tail, offset.abs)
end
end | ruby | def partially_loaded?(offset, limit = 1)
if offset >= 0
lazy_possible?(head, offset + limit)
else
lazy_possible?(tail, offset.abs)
end
end | [
"def",
"partially_loaded?",
"(",
"offset",
",",
"limit",
"=",
"1",
")",
"if",
"offset",
">=",
"0",
"lazy_possible?",
"(",
"head",
",",
"offset",
"+",
"limit",
")",
"else",
"lazy_possible?",
"(",
"tail",
",",
"offset",
".",
"abs",
")",
"end",
"end"
] | Test if the collection is loaded between the offset and limit
@param [Integer] offset
the offset of the collection to test
@param [Integer] limit
optional limit for how many entries to be loaded
@return [Boolean]
true if the collection is loaded from the offset to the limit
@api private | [
"Test",
"if",
"the",
"collection",
"is",
"loaded",
"between",
"the",
"offset",
"and",
"limit"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1095-L1101 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.lazy_load | def lazy_load
if loaded?
return self
end
mark_loaded
head = self.head
tail = self.tail
query = self.query
resources = repository.read(query)
# remove already known results
resources -= head if head.any?
resources -= tail if tail.any?
resources -= @removed.to_a if @removed.any?
query.add_reversed? ? unshift(*resources.reverse) : concat(resources)
# TODO: DRY this up with LazyArray
@array.unshift(*head)
@array.concat(tail)
@head = @tail = nil
@reapers.each { |resource| @array.delete_if(&resource) } if @reapers
@array.freeze if frozen?
self
end | ruby | def lazy_load
if loaded?
return self
end
mark_loaded
head = self.head
tail = self.tail
query = self.query
resources = repository.read(query)
# remove already known results
resources -= head if head.any?
resources -= tail if tail.any?
resources -= @removed.to_a if @removed.any?
query.add_reversed? ? unshift(*resources.reverse) : concat(resources)
# TODO: DRY this up with LazyArray
@array.unshift(*head)
@array.concat(tail)
@head = @tail = nil
@reapers.each { |resource| @array.delete_if(&resource) } if @reapers
@array.freeze if frozen?
self
end | [
"def",
"lazy_load",
"if",
"loaded?",
"return",
"self",
"end",
"mark_loaded",
"head",
"=",
"self",
".",
"head",
"tail",
"=",
"self",
".",
"tail",
"query",
"=",
"self",
".",
"query",
"resources",
"=",
"repository",
".",
"read",
"(",
"query",
")",
"# remove already known results",
"resources",
"-=",
"head",
"if",
"head",
".",
"any?",
"resources",
"-=",
"tail",
"if",
"tail",
".",
"any?",
"resources",
"-=",
"@removed",
".",
"to_a",
"if",
"@removed",
".",
"any?",
"query",
".",
"add_reversed?",
"?",
"unshift",
"(",
"resources",
".",
"reverse",
")",
":",
"concat",
"(",
"resources",
")",
"# TODO: DRY this up with LazyArray",
"@array",
".",
"unshift",
"(",
"head",
")",
"@array",
".",
"concat",
"(",
"tail",
")",
"@head",
"=",
"@tail",
"=",
"nil",
"@reapers",
".",
"each",
"{",
"|",
"resource",
"|",
"@array",
".",
"delete_if",
"(",
"resource",
")",
"}",
"if",
"@reapers",
"@array",
".",
"freeze",
"if",
"frozen?",
"self",
"end"
] | Lazy loads a Collection
@return [self]
@api private | [
"Lazy",
"loads",
"a",
"Collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1108-L1137 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.new_collection | def new_collection(query, resources = nil, &block)
if loaded?
resources ||= filter(query)
end
# TOOD: figure out a way to pass not-yet-saved Resources to this newly
# created Collection. If the new resource matches the conditions, then
# it should be added to the collection (keep in mind limit/offset too)
self.class.new(query, resources, &block)
end | ruby | def new_collection(query, resources = nil, &block)
if loaded?
resources ||= filter(query)
end
# TOOD: figure out a way to pass not-yet-saved Resources to this newly
# created Collection. If the new resource matches the conditions, then
# it should be added to the collection (keep in mind limit/offset too)
self.class.new(query, resources, &block)
end | [
"def",
"new_collection",
"(",
"query",
",",
"resources",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"loaded?",
"resources",
"||=",
"filter",
"(",
"query",
")",
"end",
"# TOOD: figure out a way to pass not-yet-saved Resources to this newly",
"# created Collection. If the new resource matches the conditions, then",
"# it should be added to the collection (keep in mind limit/offset too)",
"self",
".",
"class",
".",
"new",
"(",
"query",
",",
"resources",
",",
"block",
")",
"end"
] | Initializes a new Collection
@return [Collection]
A new Collection object
@api private | [
"Initializes",
"a",
"new",
"Collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1155-L1165 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.set_operation | def set_operation(operation, other)
resources = set_operation_resources(operation, other)
other_query = Query.target_query(repository, model, other)
new_collection(query.send(operation, other_query), resources)
end | ruby | def set_operation(operation, other)
resources = set_operation_resources(operation, other)
other_query = Query.target_query(repository, model, other)
new_collection(query.send(operation, other_query), resources)
end | [
"def",
"set_operation",
"(",
"operation",
",",
"other",
")",
"resources",
"=",
"set_operation_resources",
"(",
"operation",
",",
"other",
")",
"other_query",
"=",
"Query",
".",
"target_query",
"(",
"repository",
",",
"model",
",",
"other",
")",
"new_collection",
"(",
"query",
".",
"send",
"(",
"operation",
",",
"other_query",
")",
",",
"resources",
")",
"end"
] | Apply a set operation on self and another collection
@param [Symbol] operation
the set operation to apply
@param [Collection] other
the other collection to apply the set operation on
@return [Collection]
the collection that was created for the set operation
@api private | [
"Apply",
"a",
"set",
"operation",
"on",
"self",
"and",
"another",
"collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1178-L1182 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection._create | def _create(attributes, execute_hooks = true)
resource = repository.scope { model.send(execute_hooks ? :create : :create!, default_attributes.merge(attributes)) }
self << resource if resource.saved?
resource
end | ruby | def _create(attributes, execute_hooks = true)
resource = repository.scope { model.send(execute_hooks ? :create : :create!, default_attributes.merge(attributes)) }
self << resource if resource.saved?
resource
end | [
"def",
"_create",
"(",
"attributes",
",",
"execute_hooks",
"=",
"true",
")",
"resource",
"=",
"repository",
".",
"scope",
"{",
"model",
".",
"send",
"(",
"execute_hooks",
"?",
":create",
":",
":create!",
",",
"default_attributes",
".",
"merge",
"(",
"attributes",
")",
")",
"}",
"self",
"<<",
"resource",
"if",
"resource",
".",
"saved?",
"resource",
"end"
] | Creates a resource in the collection
@param [Boolean] execute_hooks
Whether to execute hooks or not
@param [Hash] attributes
Attributes with which to create the new resource
@return [Resource]
a saved Resource
@api private | [
"Creates",
"a",
"resource",
"in",
"the",
"collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1212-L1216 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection._save | def _save(execute_hooks = true)
loaded_entries = self.loaded_entries
loaded_entries.each { |resource| set_default_attributes(resource) }
@removed.clear
loaded_entries.all? { |resource| resource.__send__(execute_hooks ? :save : :save!) }
end | ruby | def _save(execute_hooks = true)
loaded_entries = self.loaded_entries
loaded_entries.each { |resource| set_default_attributes(resource) }
@removed.clear
loaded_entries.all? { |resource| resource.__send__(execute_hooks ? :save : :save!) }
end | [
"def",
"_save",
"(",
"execute_hooks",
"=",
"true",
")",
"loaded_entries",
"=",
"self",
".",
"loaded_entries",
"loaded_entries",
".",
"each",
"{",
"|",
"resource",
"|",
"set_default_attributes",
"(",
"resource",
")",
"}",
"@removed",
".",
"clear",
"loaded_entries",
".",
"all?",
"{",
"|",
"resource",
"|",
"resource",
".",
"__send__",
"(",
"execute_hooks",
"?",
":save",
":",
":save!",
")",
"}",
"end"
] | Saves a collection
@param [Boolean] execute_hooks
Whether to execute hooks or not
@return [Boolean]
Returns true if collection was updated
@api private | [
"Saves",
"a",
"collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1238-L1243 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.default_attributes | def default_attributes
return @default_attributes if @default_attributes
default_attributes = {}
conditions = query.conditions
if conditions.slug == :and
model_properties = properties.dup
model_key = self.model_key
if model_properties.to_set.superset?(model_key.to_set)
model_properties -= model_key
end
conditions.each do |condition|
next unless condition.slug == :eql
subject = condition.subject
next unless model_properties.include?(subject) || (condition.relationship? && subject.source_model == model)
default_attributes[subject] = condition.loaded_value
end
end
@default_attributes = default_attributes.freeze
end | ruby | def default_attributes
return @default_attributes if @default_attributes
default_attributes = {}
conditions = query.conditions
if conditions.slug == :and
model_properties = properties.dup
model_key = self.model_key
if model_properties.to_set.superset?(model_key.to_set)
model_properties -= model_key
end
conditions.each do |condition|
next unless condition.slug == :eql
subject = condition.subject
next unless model_properties.include?(subject) || (condition.relationship? && subject.source_model == model)
default_attributes[subject] = condition.loaded_value
end
end
@default_attributes = default_attributes.freeze
end | [
"def",
"default_attributes",
"return",
"@default_attributes",
"if",
"@default_attributes",
"default_attributes",
"=",
"{",
"}",
"conditions",
"=",
"query",
".",
"conditions",
"if",
"conditions",
".",
"slug",
"==",
":and",
"model_properties",
"=",
"properties",
".",
"dup",
"model_key",
"=",
"self",
".",
"model_key",
"if",
"model_properties",
".",
"to_set",
".",
"superset?",
"(",
"model_key",
".",
"to_set",
")",
"model_properties",
"-=",
"model_key",
"end",
"conditions",
".",
"each",
"do",
"|",
"condition",
"|",
"next",
"unless",
"condition",
".",
"slug",
"==",
":eql",
"subject",
"=",
"condition",
".",
"subject",
"next",
"unless",
"model_properties",
".",
"include?",
"(",
"subject",
")",
"||",
"(",
"condition",
".",
"relationship?",
"&&",
"subject",
".",
"source_model",
"==",
"model",
")",
"default_attributes",
"[",
"subject",
"]",
"=",
"condition",
".",
"loaded_value",
"end",
"end",
"@default_attributes",
"=",
"default_attributes",
".",
"freeze",
"end"
] | Returns default values to initialize new Resources in the Collection
@return [Hash] The default attributes for new instances in this Collection
@api private | [
"Returns",
"default",
"values",
"to",
"initialize",
"new",
"Resources",
"in",
"the",
"Collection"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1250-L1276 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.resource_added | def resource_added(resource)
resource = initialize_resource(resource)
if resource.saved?
@identity_map[resource.key] = resource
@removed.delete(resource)
else
set_default_attributes(resource)
end
resource
end | ruby | def resource_added(resource)
resource = initialize_resource(resource)
if resource.saved?
@identity_map[resource.key] = resource
@removed.delete(resource)
else
set_default_attributes(resource)
end
resource
end | [
"def",
"resource_added",
"(",
"resource",
")",
"resource",
"=",
"initialize_resource",
"(",
"resource",
")",
"if",
"resource",
".",
"saved?",
"@identity_map",
"[",
"resource",
".",
"key",
"]",
"=",
"resource",
"@removed",
".",
"delete",
"(",
"resource",
")",
"else",
"set_default_attributes",
"(",
"resource",
")",
"end",
"resource",
"end"
] | Track the added resource
@param [Resource] resource
the resource that was added
@return [Resource]
the resource that was added
@api private | [
"Track",
"the",
"added",
"resource"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1301-L1312 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.resources_added | def resources_added(resources)
if resources.kind_of?(Enumerable)
resources.map { |resource| resource_added(resource) }
else
resource_added(resources)
end
end | ruby | def resources_added(resources)
if resources.kind_of?(Enumerable)
resources.map { |resource| resource_added(resource) }
else
resource_added(resources)
end
end | [
"def",
"resources_added",
"(",
"resources",
")",
"if",
"resources",
".",
"kind_of?",
"(",
"Enumerable",
")",
"resources",
".",
"map",
"{",
"|",
"resource",
"|",
"resource_added",
"(",
"resource",
")",
"}",
"else",
"resource_added",
"(",
"resources",
")",
"end",
"end"
] | Track the added resources
@param [Array<Resource>] resources
the resources that were added
@return [Array<Resource>]
the resources that were added
@api private | [
"Track",
"the",
"added",
"resources"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1323-L1329 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.resources_removed | def resources_removed(resources)
if resources.kind_of?(Enumerable)
resources.each { |resource| resource_removed(resource) }
else
resource_removed(resources)
end
end | ruby | def resources_removed(resources)
if resources.kind_of?(Enumerable)
resources.each { |resource| resource_removed(resource) }
else
resource_removed(resources)
end
end | [
"def",
"resources_removed",
"(",
"resources",
")",
"if",
"resources",
".",
"kind_of?",
"(",
"Enumerable",
")",
"resources",
".",
"each",
"{",
"|",
"resource",
"|",
"resource_removed",
"(",
"resource",
")",
"}",
"else",
"resource_removed",
"(",
"resources",
")",
"end",
"end"
] | Track the removed resources
@param [Array<Resource>] resources
the resources that were removed
@return [Array<Resource>]
the resources that were removed
@api private | [
"Track",
"the",
"removed",
"resources"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1358-L1364 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.filter | def filter(other_query)
query = self.query
fields = query.fields.to_set
unique = other_query.unique?
# TODO: push this into a Query#subset? method
if other_query.links.empty? &&
(unique || (!unique && !query.unique?)) &&
!other_query.reload? &&
!other_query.raw? &&
other_query.fields.to_set.subset?(fields) &&
other_query.condition_properties.subset?(fields)
then
other_query.filter_records(to_a.dup)
end
end | ruby | def filter(other_query)
query = self.query
fields = query.fields.to_set
unique = other_query.unique?
# TODO: push this into a Query#subset? method
if other_query.links.empty? &&
(unique || (!unique && !query.unique?)) &&
!other_query.reload? &&
!other_query.raw? &&
other_query.fields.to_set.subset?(fields) &&
other_query.condition_properties.subset?(fields)
then
other_query.filter_records(to_a.dup)
end
end | [
"def",
"filter",
"(",
"other_query",
")",
"query",
"=",
"self",
".",
"query",
"fields",
"=",
"query",
".",
"fields",
".",
"to_set",
"unique",
"=",
"other_query",
".",
"unique?",
"# TODO: push this into a Query#subset? method",
"if",
"other_query",
".",
"links",
".",
"empty?",
"&&",
"(",
"unique",
"||",
"(",
"!",
"unique",
"&&",
"!",
"query",
".",
"unique?",
")",
")",
"&&",
"!",
"other_query",
".",
"reload?",
"&&",
"!",
"other_query",
".",
"raw?",
"&&",
"other_query",
".",
"fields",
".",
"to_set",
".",
"subset?",
"(",
"fields",
")",
"&&",
"other_query",
".",
"condition_properties",
".",
"subset?",
"(",
"fields",
")",
"then",
"other_query",
".",
"filter_records",
"(",
"to_a",
".",
"dup",
")",
"end",
"end"
] | Filter resources in the collection based on a Query
@param [Query] query
the query to match each resource in the collection
@return [Array]
the resources that match the Query
@return [nil]
nil if no resources match the Query
@api private | [
"Filter",
"resources",
"in",
"the",
"collection",
"based",
"on",
"a",
"Query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1377-L1392 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.scoped_query | def scoped_query(query)
if query.kind_of?(Query)
query.dup
else
self.query.relative(query)
end
end | ruby | def scoped_query(query)
if query.kind_of?(Query)
query.dup
else
self.query.relative(query)
end
end | [
"def",
"scoped_query",
"(",
"query",
")",
"if",
"query",
".",
"kind_of?",
"(",
"Query",
")",
"query",
".",
"dup",
"else",
"self",
".",
"query",
".",
"relative",
"(",
"query",
")",
"end",
"end"
] | Return the absolute or relative scoped query
@param [Query, Hash] query
the query to scope the collection with
@return [Query]
the absolute or relative scoped query
@api private | [
"Return",
"the",
"absolute",
"or",
"relative",
"scoped",
"query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1403-L1409 | train |
datamapper/dm-core | lib/dm-core/collection.rb | DataMapper.Collection.delegate_to_model | def delegate_to_model(method, *args, &block)
model = self.model
model.send(:with_scope, query) do
model.send(method, *args, &block)
end
end | ruby | def delegate_to_model(method, *args, &block)
model = self.model
model.send(:with_scope, query) do
model.send(method, *args, &block)
end
end | [
"def",
"delegate_to_model",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"model",
"=",
"self",
".",
"model",
"model",
".",
"send",
"(",
":with_scope",
",",
"query",
")",
"do",
"model",
".",
"send",
"(",
"method",
",",
"args",
",",
"block",
")",
"end",
"end"
] | Delegate the method to the Model
@param [Symbol] method
the name of the method in the model to execute
@param [Array] *args
the arguments for the method
@return [Object]
the return value of the model method
@api private | [
"Delegate",
"the",
"method",
"to",
"the",
"Model"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/collection.rb#L1465-L1470 | train |
datamapper/dm-core | lib/dm-core/repository.rb | DataMapper.Repository.read | def read(query)
return [] unless query.valid?
query.model.load(adapter.read(query), query)
end | ruby | def read(query)
return [] unless query.valid?
query.model.load(adapter.read(query), query)
end | [
"def",
"read",
"(",
"query",
")",
"return",
"[",
"]",
"unless",
"query",
".",
"valid?",
"query",
".",
"model",
".",
"load",
"(",
"adapter",
".",
"read",
"(",
"query",
")",
",",
"query",
")",
"end"
] | Retrieve a collection of results of a query
TODO: create example
@param [Query] query
composition of the query to perform
@return [Array]
result set of the query
@api semipublic | [
"Retrieve",
"a",
"collection",
"of",
"results",
"of",
"a",
"query"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/repository.rb#L160-L163 | train |
datamapper/dm-core | lib/dm-core/repository.rb | DataMapper.Repository.update | def update(attributes, collection)
return 0 unless collection.query.valid? && attributes.any?
adapter.update(attributes, collection)
end | ruby | def update(attributes, collection)
return 0 unless collection.query.valid? && attributes.any?
adapter.update(attributes, collection)
end | [
"def",
"update",
"(",
"attributes",
",",
"collection",
")",
"return",
"0",
"unless",
"collection",
".",
"query",
".",
"valid?",
"&&",
"attributes",
".",
"any?",
"adapter",
".",
"update",
"(",
"attributes",
",",
"collection",
")",
"end"
] | Update the attributes of one or more resource instances
TODO: create example
@param [Hash(Property => Object)] attributes
hash of attribute values to set, keyed by Property
@param [Collection] collection
collection of records to be updated
@return [Integer]
the number of records updated
@api semipublic | [
"Update",
"the",
"attributes",
"of",
"one",
"or",
"more",
"resource",
"instances"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/repository.rb#L178-L181 | train |
datamapper/dm-core | lib/dm-core/support/descendant_set.rb | DataMapper.DescendantSet.delete | def delete(descendant)
@descendants.delete(descendant)
each { |d| d.descendants.delete(descendant) }
end | ruby | def delete(descendant)
@descendants.delete(descendant)
each { |d| d.descendants.delete(descendant) }
end | [
"def",
"delete",
"(",
"descendant",
")",
"@descendants",
".",
"delete",
"(",
"descendant",
")",
"each",
"{",
"|",
"d",
"|",
"d",
".",
"descendants",
".",
"delete",
"(",
"descendant",
")",
"}",
"end"
] | Remove a descendant
Also removes from all descendants
@param [Module] descendant
@return [DescendantSet]
self
@api private | [
"Remove",
"a",
"descendant"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/support/descendant_set.rb#L48-L51 | train |
datamapper/dm-core | lib/dm-core/property.rb | DataMapper.Property.valid? | def valid?(value, negated = false)
dumped_value = dump(value)
if required? && dumped_value.nil?
negated || false
else
value_dumped?(dumped_value) || (dumped_value.nil? && (allow_nil? || negated))
end
end | ruby | def valid?(value, negated = false)
dumped_value = dump(value)
if required? && dumped_value.nil?
negated || false
else
value_dumped?(dumped_value) || (dumped_value.nil? && (allow_nil? || negated))
end
end | [
"def",
"valid?",
"(",
"value",
",",
"negated",
"=",
"false",
")",
"dumped_value",
"=",
"dump",
"(",
"value",
")",
"if",
"required?",
"&&",
"dumped_value",
".",
"nil?",
"negated",
"||",
"false",
"else",
"value_dumped?",
"(",
"dumped_value",
")",
"||",
"(",
"dumped_value",
".",
"nil?",
"&&",
"(",
"allow_nil?",
"||",
"negated",
")",
")",
"end",
"end"
] | Test the value to see if it is a valid value for this Property
@param [Object] loaded_value
the value to be tested
@return [Boolean]
true if the value is valid
@api semipulic | [
"Test",
"the",
"value",
"to",
"see",
"if",
"it",
"is",
"a",
"valid",
"value",
"for",
"this",
"Property"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/property.rb#L695-L703 | train |
datamapper/dm-core | lib/dm-core/property.rb | DataMapper.Property.assert_valid_value | def assert_valid_value(value)
unless valid?(value)
raise Property::InvalidValueError.new(self,value)
end
true
end | ruby | def assert_valid_value(value)
unless valid?(value)
raise Property::InvalidValueError.new(self,value)
end
true
end | [
"def",
"assert_valid_value",
"(",
"value",
")",
"unless",
"valid?",
"(",
"value",
")",
"raise",
"Property",
"::",
"InvalidValueError",
".",
"new",
"(",
"self",
",",
"value",
")",
"end",
"true",
"end"
] | Asserts value is valid
@param [Object] loaded_value
the value to be tested
@return [Boolean]
true if the value is valid
@raise [Property::InvalidValueError]
if value is not valid | [
"Asserts",
"value",
"is",
"valid"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/property.rb#L715-L720 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.attribute_set | def attribute_set(name, value)
property = properties[name]
if property
value = property.typecast(value)
self.persistence_state = persistence_state.set(property, value)
end
end | ruby | def attribute_set(name, value)
property = properties[name]
if property
value = property.typecast(value)
self.persistence_state = persistence_state.set(property, value)
end
end | [
"def",
"attribute_set",
"(",
"name",
",",
"value",
")",
"property",
"=",
"properties",
"[",
"name",
"]",
"if",
"property",
"value",
"=",
"property",
".",
"typecast",
"(",
"value",
")",
"self",
".",
"persistence_state",
"=",
"persistence_state",
".",
"set",
"(",
"property",
",",
"value",
")",
"end",
"end"
] | Sets the value of the attribute and marks the attribute as dirty
if it has been changed so that it may be saved. Do not set from
instance variables directly, but use this method. This method
handles the lazy loading the property and returning of defaults
if nessesary.
@example
class Foo
include DataMapper::Resource
property :first_name, String
property :last_name, String
def full_name(name)
name = name.split(' ')
attribute_set(:first_name, name[0])
attribute_set(:last_name, name[1])
end
# using the shorter syntax
def name_from_address_book(name)
name = name.split(', ')
self.first_name = name[1]
self.last_name = name[0]
end
end
@param [Symbol] name
name of attribute to set
@param [Object] value
value to store
@return [undefined]
@api public | [
"Sets",
"the",
"value",
"of",
"the",
"attribute",
"and",
"marks",
"the",
"attribute",
"as",
"dirty",
"if",
"it",
"has",
"been",
"changed",
"so",
"that",
"it",
"may",
"be",
"saved",
".",
"Do",
"not",
"set",
"from",
"instance",
"variables",
"directly",
"but",
"use",
"this",
"method",
".",
"This",
"method",
"handles",
"the",
"lazy",
"loading",
"the",
"property",
"and",
"returning",
"of",
"defaults",
"if",
"nessesary",
"."
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L267-L273 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.attributes | def attributes(key_on = :name)
attributes = {}
lazy_load(properties)
fields.each do |property|
if model.public_method_defined?(name = property.name)
key = case key_on
when :name then name
when :field then property.field
else property
end
attributes[key] = __send__(name)
end
end
attributes
end | ruby | def attributes(key_on = :name)
attributes = {}
lazy_load(properties)
fields.each do |property|
if model.public_method_defined?(name = property.name)
key = case key_on
when :name then name
when :field then property.field
else property
end
attributes[key] = __send__(name)
end
end
attributes
end | [
"def",
"attributes",
"(",
"key_on",
"=",
":name",
")",
"attributes",
"=",
"{",
"}",
"lazy_load",
"(",
"properties",
")",
"fields",
".",
"each",
"do",
"|",
"property",
"|",
"if",
"model",
".",
"public_method_defined?",
"(",
"name",
"=",
"property",
".",
"name",
")",
"key",
"=",
"case",
"key_on",
"when",
":name",
"then",
"name",
"when",
":field",
"then",
"property",
".",
"field",
"else",
"property",
"end",
"attributes",
"[",
"key",
"]",
"=",
"__send__",
"(",
"name",
")",
"end",
"end",
"attributes",
"end"
] | Gets all the attributes of the Resource instance
@param [Symbol] key_on
Use this attribute of the Property as keys.
defaults to :name. :field is useful for adapters
:property or nil use the actual Property object.
@return [Hash]
All the attributes
@api public | [
"Gets",
"all",
"the",
"attributes",
"of",
"the",
"Resource",
"instance"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L288-L305 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.inspect | def inspect
# TODO: display relationship values
attrs = properties.map do |property|
value = if new? || property.loaded?(self)
property.get!(self).inspect
else
'<not loaded>'
end
"#{property.instance_variable_name}=#{value}"
end
"#<#{model.name} #{attrs.join(' ')}>"
end | ruby | def inspect
# TODO: display relationship values
attrs = properties.map do |property|
value = if new? || property.loaded?(self)
property.get!(self).inspect
else
'<not loaded>'
end
"#{property.instance_variable_name}=#{value}"
end
"#<#{model.name} #{attrs.join(' ')}>"
end | [
"def",
"inspect",
"# TODO: display relationship values",
"attrs",
"=",
"properties",
".",
"map",
"do",
"|",
"property",
"|",
"value",
"=",
"if",
"new?",
"||",
"property",
".",
"loaded?",
"(",
"self",
")",
"property",
".",
"get!",
"(",
"self",
")",
".",
"inspect",
"else",
"'<not loaded>'",
"end",
"\"#{property.instance_variable_name}=#{value}\"",
"end",
"\"#<#{model.name} #{attrs.join(' ')}>\"",
"end"
] | Compares another Resource for equality
Resource is equal to +other+ if they are the same object
(identical object_id) or if they are both of the *same model* and
all of their attributes are equivalent
@param [Resource] other
the other Resource to compare with
@return [Boolean]
true if they are equal, false if not
@api public
Compares another Resource for equivalency
Resource is equivalent to +other+ if they are the same object
(identical object_id) or all of their attribute are equivalent
@param [Resource] other
the other Resource to compare with
@return [Boolean]
true if they are equivalent, false if not
@api public
Compares two Resources to allow them to be sorted
@param [Resource] other
The other Resource to compare with
@return [Integer]
Return 0 if Resources should be sorted as the same, -1 if the
other Resource should be after self, and 1 if the other Resource
should be before self
@api public
Returns hash value of the object.
Two objects with the same hash value assumed equal (using eql? method)
DataMapper resources are equal when their models have the same hash
and they have the same set of properties
When used as key in a Hash or Hash subclass, objects are compared
by eql? and thus hash value has direct effect on lookup
@api private
Get a Human-readable representation of this Resource instance
Foo.new #=> #<Foo name=nil updated_at=nil created_at=nil id=nil>
@return [String]
Human-readable representation of this Resource instance
@api public | [
"Compares",
"another",
"Resource",
"for",
"equality"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L525-L538 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.dirty_attributes | def dirty_attributes
dirty_attributes = {}
original_attributes.each_key do |property|
next unless property.respond_to?(:dump)
dirty_attributes[property] = property.dump(property.get!(self))
end
dirty_attributes
end | ruby | def dirty_attributes
dirty_attributes = {}
original_attributes.each_key do |property|
next unless property.respond_to?(:dump)
dirty_attributes[property] = property.dump(property.get!(self))
end
dirty_attributes
end | [
"def",
"dirty_attributes",
"dirty_attributes",
"=",
"{",
"}",
"original_attributes",
".",
"each_key",
"do",
"|",
"property",
"|",
"next",
"unless",
"property",
".",
"respond_to?",
"(",
":dump",
")",
"dirty_attributes",
"[",
"property",
"]",
"=",
"property",
".",
"dump",
"(",
"property",
".",
"get!",
"(",
"self",
")",
")",
"end",
"dirty_attributes",
"end"
] | Hash of attributes that have unsaved changes
@return [Hash]
attributes that have unsaved changes
@api semipublic | [
"Hash",
"of",
"attributes",
"that",
"have",
"unsaved",
"changes"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L596-L605 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.initialize_copy | def initialize_copy(original)
instance_variables.each do |ivar|
instance_variable_set(ivar, DataMapper::Ext.try_dup(instance_variable_get(ivar)))
end
self.persistence_state = persistence_state.class.new(self)
end | ruby | def initialize_copy(original)
instance_variables.each do |ivar|
instance_variable_set(ivar, DataMapper::Ext.try_dup(instance_variable_get(ivar)))
end
self.persistence_state = persistence_state.class.new(self)
end | [
"def",
"initialize_copy",
"(",
"original",
")",
"instance_variables",
".",
"each",
"do",
"|",
"ivar",
"|",
"instance_variable_set",
"(",
"ivar",
",",
"DataMapper",
"::",
"Ext",
".",
"try_dup",
"(",
"instance_variable_get",
"(",
"ivar",
")",
")",
")",
"end",
"self",
".",
"persistence_state",
"=",
"persistence_state",
".",
"class",
".",
"new",
"(",
"self",
")",
"end"
] | Initialize a new instance of this Resource using the provided values
@param [Hash] attributes
attribute values to use for the new instance
@return [Hash]
attribute values used in the new instance
@api public
@api private | [
"Initialize",
"a",
"new",
"instance",
"of",
"this",
"Resource",
"using",
"the",
"provided",
"values"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L745-L751 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.reset_key | def reset_key
properties.key.zip(key) do |property, value|
property.set!(self, value)
end
end | ruby | def reset_key
properties.key.zip(key) do |property, value|
property.set!(self, value)
end
end | [
"def",
"reset_key",
"properties",
".",
"key",
".",
"zip",
"(",
"key",
")",
"do",
"|",
"property",
",",
"value",
"|",
"property",
".",
"set!",
"(",
"self",
",",
"value",
")",
"end",
"end"
] | Reset the key to the original value
@return [undefined]
@api private | [
"Reset",
"the",
"key",
"to",
"the",
"original",
"value"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L822-L826 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.clear_subjects | def clear_subjects
model_properties = properties
(model_properties - model_properties.key | relationships).each do |subject|
next unless subject.loaded?(self)
remove_instance_variable(subject.instance_variable_name)
end
end | ruby | def clear_subjects
model_properties = properties
(model_properties - model_properties.key | relationships).each do |subject|
next unless subject.loaded?(self)
remove_instance_variable(subject.instance_variable_name)
end
end | [
"def",
"clear_subjects",
"model_properties",
"=",
"properties",
"(",
"model_properties",
"-",
"model_properties",
".",
"key",
"|",
"relationships",
")",
".",
"each",
"do",
"|",
"subject",
"|",
"next",
"unless",
"subject",
".",
"loaded?",
"(",
"self",
")",
"remove_instance_variable",
"(",
"subject",
".",
"instance_variable_name",
")",
"end",
"end"
] | Remove all the ivars for properties and relationships
@return [undefined]
@api private | [
"Remove",
"all",
"the",
"ivars",
"for",
"properties",
"and",
"relationships"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L833-L840 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.eager_load | def eager_load(properties)
unless properties.empty? || key.nil? || collection.nil?
# set an initial value to prevent recursive lazy loads
properties.each { |property| property.set!(self, nil) }
collection.reload(:fields => properties)
end
self
end | ruby | def eager_load(properties)
unless properties.empty? || key.nil? || collection.nil?
# set an initial value to prevent recursive lazy loads
properties.each { |property| property.set!(self, nil) }
collection.reload(:fields => properties)
end
self
end | [
"def",
"eager_load",
"(",
"properties",
")",
"unless",
"properties",
".",
"empty?",
"||",
"key",
".",
"nil?",
"||",
"collection",
".",
"nil?",
"# set an initial value to prevent recursive lazy loads",
"properties",
".",
"each",
"{",
"|",
"property",
"|",
"property",
".",
"set!",
"(",
"self",
",",
"nil",
")",
"}",
"collection",
".",
"reload",
"(",
":fields",
"=>",
"properties",
")",
"end",
"self",
"end"
] | Reloads specified attributes
@param [Array<Property>] properties
the properties to reload
@return [Resource]
the receiver, the current Resource instance
@api private | [
"Reloads",
"specified",
"attributes"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L863-L872 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.conditions | def conditions
key = self.key
if key
model.key_conditions(repository, key)
else
conditions = {}
properties.each do |property|
next unless property.loaded?(self)
conditions[property] = property.get!(self)
end
conditions
end
end | ruby | def conditions
key = self.key
if key
model.key_conditions(repository, key)
else
conditions = {}
properties.each do |property|
next unless property.loaded?(self)
conditions[property] = property.get!(self)
end
conditions
end
end | [
"def",
"conditions",
"key",
"=",
"self",
".",
"key",
"if",
"key",
"model",
".",
"key_conditions",
"(",
"repository",
",",
"key",
")",
"else",
"conditions",
"=",
"{",
"}",
"properties",
".",
"each",
"do",
"|",
"property",
"|",
"next",
"unless",
"property",
".",
"loaded?",
"(",
"self",
")",
"conditions",
"[",
"property",
"]",
"=",
"property",
".",
"get!",
"(",
"self",
")",
"end",
"conditions",
"end",
"end"
] | Return conditions to match the Resource
@return [Hash]
query conditions
@api private | [
"Return",
"conditions",
"to",
"match",
"the",
"Resource"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L880-L892 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.child_relationships | def child_relationships
child_relationships = []
relationships.each do |relationship|
next unless relationship.respond_to?(:collection_for)
set_default_value(relationship)
next unless relationship.loaded?(self)
child_relationships << relationship
end
many_to_many, other = child_relationships.partition do |relationship|
relationship.kind_of?(Associations::ManyToMany::Relationship)
end
many_to_many + other
end | ruby | def child_relationships
child_relationships = []
relationships.each do |relationship|
next unless relationship.respond_to?(:collection_for)
set_default_value(relationship)
next unless relationship.loaded?(self)
child_relationships << relationship
end
many_to_many, other = child_relationships.partition do |relationship|
relationship.kind_of?(Associations::ManyToMany::Relationship)
end
many_to_many + other
end | [
"def",
"child_relationships",
"child_relationships",
"=",
"[",
"]",
"relationships",
".",
"each",
"do",
"|",
"relationship",
"|",
"next",
"unless",
"relationship",
".",
"respond_to?",
"(",
":collection_for",
")",
"set_default_value",
"(",
"relationship",
")",
"next",
"unless",
"relationship",
".",
"loaded?",
"(",
"self",
")",
"child_relationships",
"<<",
"relationship",
"end",
"many_to_many",
",",
"other",
"=",
"child_relationships",
".",
"partition",
"do",
"|",
"relationship",
"|",
"relationship",
".",
"kind_of?",
"(",
"Associations",
"::",
"ManyToMany",
"::",
"Relationship",
")",
"end",
"many_to_many",
"+",
"other",
"end"
] | Returns loaded child relationships
@return [Array<Associations::OneToMany::Relationship>]
array of child relationships for which this resource is parent and is loaded
@api private | [
"Returns",
"loaded",
"child",
"relationships"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L915-L931 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.save_self | def save_self(execute_hooks = true)
# short-circuit if the resource is not dirty
return saved? unless dirty_self?
if execute_hooks
new? ? create_with_hooks : update_with_hooks
else
_persist
end
clean?
end | ruby | def save_self(execute_hooks = true)
# short-circuit if the resource is not dirty
return saved? unless dirty_self?
if execute_hooks
new? ? create_with_hooks : update_with_hooks
else
_persist
end
clean?
end | [
"def",
"save_self",
"(",
"execute_hooks",
"=",
"true",
")",
"# short-circuit if the resource is not dirty",
"return",
"saved?",
"unless",
"dirty_self?",
"if",
"execute_hooks",
"new?",
"?",
"create_with_hooks",
":",
"update_with_hooks",
"else",
"_persist",
"end",
"clean?",
"end"
] | Saves the resource
@return [Boolean]
true if the resource was successfully saved
@api semipublic | [
"Saves",
"the",
"resource"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1009-L1019 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.save_parents | def save_parents(execute_hooks)
run_once(true) do
parent_relationships.map do |relationship|
parent = relationship.get(self)
if parent.__send__(:save_parents, execute_hooks) && parent.__send__(:save_self, execute_hooks)
relationship.set(self, parent) # set the FK values
end
end.all?
end
end | ruby | def save_parents(execute_hooks)
run_once(true) do
parent_relationships.map do |relationship|
parent = relationship.get(self)
if parent.__send__(:save_parents, execute_hooks) && parent.__send__(:save_self, execute_hooks)
relationship.set(self, parent) # set the FK values
end
end.all?
end
end | [
"def",
"save_parents",
"(",
"execute_hooks",
")",
"run_once",
"(",
"true",
")",
"do",
"parent_relationships",
".",
"map",
"do",
"|",
"relationship",
"|",
"parent",
"=",
"relationship",
".",
"get",
"(",
"self",
")",
"if",
"parent",
".",
"__send__",
"(",
":save_parents",
",",
"execute_hooks",
")",
"&&",
"parent",
".",
"__send__",
"(",
":save_self",
",",
"execute_hooks",
")",
"relationship",
".",
"set",
"(",
"self",
",",
"parent",
")",
"# set the FK values",
"end",
"end",
".",
"all?",
"end",
"end"
] | Saves the parent resources
@return [Boolean]
true if the parents were successfully saved
@api private | [
"Saves",
"the",
"parent",
"resources"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1027-L1037 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.dirty_self? | def dirty_self?
if original_attributes.any?
true
elsif new?
!model.serial.nil? || properties.any? { |property| property.default? }
else
false
end
end | ruby | def dirty_self?
if original_attributes.any?
true
elsif new?
!model.serial.nil? || properties.any? { |property| property.default? }
else
false
end
end | [
"def",
"dirty_self?",
"if",
"original_attributes",
".",
"any?",
"true",
"elsif",
"new?",
"!",
"model",
".",
"serial",
".",
"nil?",
"||",
"properties",
".",
"any?",
"{",
"|",
"property",
"|",
"property",
".",
"default?",
"}",
"else",
"false",
"end",
"end"
] | Checks if the resource has unsaved changes
@return [Boolean]
true if the resource has unsaved changes
@api semipublic | [
"Checks",
"if",
"the",
"resource",
"has",
"unsaved",
"changes"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1057-L1065 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.dirty_parents? | def dirty_parents?
run_once(false) do
parent_associations.any? do |association|
association.__send__(:dirty_self?) || association.__send__(:dirty_parents?)
end
end
end | ruby | def dirty_parents?
run_once(false) do
parent_associations.any? do |association|
association.__send__(:dirty_self?) || association.__send__(:dirty_parents?)
end
end
end | [
"def",
"dirty_parents?",
"run_once",
"(",
"false",
")",
"do",
"parent_associations",
".",
"any?",
"do",
"|",
"association",
"|",
"association",
".",
"__send__",
"(",
":dirty_self?",
")",
"||",
"association",
".",
"__send__",
"(",
":dirty_parents?",
")",
"end",
"end",
"end"
] | Checks if the parents have unsaved changes
@return [Boolean]
true if the parents have unsaved changes
@api private | [
"Checks",
"if",
"the",
"parents",
"have",
"unsaved",
"changes"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1073-L1079 | train |
datamapper/dm-core | lib/dm-core/resource.rb | DataMapper.Resource.cmp? | def cmp?(other, operator)
return false unless repository.send(operator, other.repository) &&
key.send(operator, other.key)
if saved? && other.saved?
# if dirty attributes match then they are the same resource
dirty_attributes == other.dirty_attributes
else
# compare properties for unsaved resources
properties.all? do |property|
__send__(property.name).send(operator, other.__send__(property.name))
end
end
end | ruby | def cmp?(other, operator)
return false unless repository.send(operator, other.repository) &&
key.send(operator, other.key)
if saved? && other.saved?
# if dirty attributes match then they are the same resource
dirty_attributes == other.dirty_attributes
else
# compare properties for unsaved resources
properties.all? do |property|
__send__(property.name).send(operator, other.__send__(property.name))
end
end
end | [
"def",
"cmp?",
"(",
"other",
",",
"operator",
")",
"return",
"false",
"unless",
"repository",
".",
"send",
"(",
"operator",
",",
"other",
".",
"repository",
")",
"&&",
"key",
".",
"send",
"(",
"operator",
",",
"other",
".",
"key",
")",
"if",
"saved?",
"&&",
"other",
".",
"saved?",
"# if dirty attributes match then they are the same resource",
"dirty_attributes",
"==",
"other",
".",
"dirty_attributes",
"else",
"# compare properties for unsaved resources",
"properties",
".",
"all?",
"do",
"|",
"property",
"|",
"__send__",
"(",
"property",
".",
"name",
")",
".",
"send",
"(",
"operator",
",",
"other",
".",
"__send__",
"(",
"property",
".",
"name",
")",
")",
"end",
"end",
"end"
] | Return true if +other+'s is equivalent or equal to +self+'s
@param [Resource] other
The Resource whose attributes are to be compared with +self+'s
@param [Symbol] operator
The comparison operator to use to compare the attributes
@return [Boolean]
The result of the comparison of +other+'s attributes with +self+'s
@api private | [
"Return",
"true",
"if",
"+",
"other",
"+",
"s",
"is",
"equivalent",
"or",
"equal",
"to",
"+",
"self",
"+",
"s"
] | 226c5af8609a2e1da3bf3ee0b29a874401a49c0b | https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1105-L1118 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.