id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
19,400
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
19,401
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
19,402
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
19,403
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
19,404
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
19,405
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
19,406
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
19,407
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
19,408
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
19,409
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
19,410
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
19,411
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
19,412
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
19,413
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
19,414
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
19,415
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
19,416
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
19,417
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
19,418
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
19,419
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
19,420
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
19,421
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
19,422
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
19,423
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
19,424
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
19,425
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
19,426
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
19,427
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
19,428
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
19,429
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
19,430
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
19,431
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
19,432
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
19,433
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
19,434
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
19,435
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
19,436
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
19,437
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
19,438
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
19,439
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
19,440
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
19,441
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
19,442
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
19,443
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
19,444
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
19,445
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
19,446
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
19,447
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
19,448
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
19,449
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
19,450
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
19,451
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
19,452
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
19,453
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
19,454
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
19,455
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
19,456
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
19,457
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
19,458
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
19,459
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
19,460
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
19,461
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
19,462
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
19,463
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
19,464
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
19,465
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
19,466
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
19,467
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
19,468
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
19,469
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
19,470
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
19,471
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
19,472
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
19,473
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
19,474
datamapper/dm-core
lib/dm-core/resource.rb
DataMapper.Resource.execute_hooks_for
def execute_hooks_for(type, name) model.hooks[name][type].each { |hook| hook.call(self) } end
ruby
def execute_hooks_for(type, name) model.hooks[name][type].each { |hook| hook.call(self) } end
[ "def", "execute_hooks_for", "(", "type", ",", "name", ")", "model", ".", "hooks", "[", "name", "]", "[", "type", "]", ".", "each", "{", "|", "hook", "|", "hook", ".", "call", "(", "self", ")", "}", "end" ]
Execute all the queued up hooks for a given type and name @param [Symbol] type the type of hook to execute (before or after) @param [Symbol] name the name of the hook to execute @return [undefined] @api private
[ "Execute", "all", "the", "queued", "up", "hooks", "for", "a", "given", "type", "and", "name" ]
226c5af8609a2e1da3bf3ee0b29a874401a49c0b
https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1136-L1138
19,475
datamapper/dm-core
lib/dm-core/resource.rb
DataMapper.Resource.run_once
def run_once(default) caller_method = Kernel.caller(1).first[/`([^'?!]+)[?!]?'/, 1] sentinel = "@_#{caller_method}_sentinel" return instance_variable_get(sentinel) if instance_variable_defined?(sentinel) begin instance_variable_set(sentinel, default) yield ensure remove_instance_variable(sentinel) end end
ruby
def run_once(default) caller_method = Kernel.caller(1).first[/`([^'?!]+)[?!]?'/, 1] sentinel = "@_#{caller_method}_sentinel" return instance_variable_get(sentinel) if instance_variable_defined?(sentinel) begin instance_variable_set(sentinel, default) yield ensure remove_instance_variable(sentinel) end end
[ "def", "run_once", "(", "default", ")", "caller_method", "=", "Kernel", ".", "caller", "(", "1", ")", ".", "first", "[", "/", "/", ",", "1", "]", "sentinel", "=", "\"@_#{caller_method}_sentinel\"", "return", "instance_variable_get", "(", "sentinel", ")", "if", "instance_variable_defined?", "(", "sentinel", ")", "begin", "instance_variable_set", "(", "sentinel", ",", "default", ")", "yield", "ensure", "remove_instance_variable", "(", "sentinel", ")", "end", "end" ]
Prevent a method from being in the stack more than once The purpose of this method is to prevent SystemStackError from being thrown from methods from encountering infinite recursion when called on resources having circular dependencies. @param [Object] default default return value @yield The block of code to run once @return [Object] block return value @api private
[ "Prevent", "a", "method", "from", "being", "in", "the", "stack", "more", "than", "once" ]
226c5af8609a2e1da3bf3ee0b29a874401a49c0b
https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/resource.rb#L1208-L1219
19,476
datamapper/dm-core
lib/dm-core/support/inflector/inflections.rb
DataMapper.Inflector.pluralize
def pluralize(word) result = word.to_s.dup if word.empty? || inflections.uncountables.include?(result.downcase) result else inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } result end end
ruby
def pluralize(word) result = word.to_s.dup if word.empty? || inflections.uncountables.include?(result.downcase) result else inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } result end end
[ "def", "pluralize", "(", "word", ")", "result", "=", "word", ".", "to_s", ".", "dup", "if", "word", ".", "empty?", "||", "inflections", ".", "uncountables", ".", "include?", "(", "result", ".", "downcase", ")", "result", "else", "inflections", ".", "plurals", ".", "each", "{", "|", "(", "rule", ",", "replacement", ")", "|", "break", "if", "result", ".", "gsub!", "(", "rule", ",", "replacement", ")", "}", "result", "end", "end" ]
Returns the plural form of the word in the string. Examples: "post".pluralize # => "posts" "octopus".pluralize # => "octopi" "sheep".pluralize # => "sheep" "words".pluralize # => "words" "CamelOctopus".pluralize # => "CamelOctopi"
[ "Returns", "the", "plural", "form", "of", "the", "word", "in", "the", "string", "." ]
226c5af8609a2e1da3bf3ee0b29a874401a49c0b
https://github.com/datamapper/dm-core/blob/226c5af8609a2e1da3bf3ee0b29a874401a49c0b/lib/dm-core/support/inflector/inflections.rb#L129-L138
19,477
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.exception_message
def exception_message(e) msg = [ "Exception #{e.class} -> #{e.message}" ] base = File.expand_path(Dir.pwd) + '/' e.backtrace.each do |t| msg << " #{File.expand_path(t).gsub(/#{base}/, '')}" end if e.backtrace msg.join("\n") end
ruby
def exception_message(e) msg = [ "Exception #{e.class} -> #{e.message}" ] base = File.expand_path(Dir.pwd) + '/' e.backtrace.each do |t| msg << " #{File.expand_path(t).gsub(/#{base}/, '')}" end if e.backtrace msg.join("\n") end
[ "def", "exception_message", "(", "e", ")", "msg", "=", "[", "\"Exception #{e.class} -> #{e.message}\"", "]", "base", "=", "File", ".", "expand_path", "(", "Dir", ".", "pwd", ")", "+", "'/'", "e", ".", "backtrace", ".", "each", "do", "|", "t", "|", "msg", "<<", "\" #{File.expand_path(t).gsub(/#{base}/, '')}\"", "end", "if", "e", ".", "backtrace", "msg", ".", "join", "(", "\"\\n\"", ")", "end" ]
Prints out exception_message based on specified e
[ "Prints", "out", "exception_message", "based", "on", "specified", "e" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L9-L18
19,478
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.classify
def classify(dashed_word) dashed_word.to_s.split('-').each { |part| part[0] = part[0].chr.upcase }.join end
ruby
def classify(dashed_word) dashed_word.to_s.split('-').each { |part| part[0] = part[0].chr.upcase }.join end
[ "def", "classify", "(", "dashed_word", ")", "dashed_word", ".", "to_s", ".", "split", "(", "'-'", ")", ".", "each", "{", "|", "part", "|", "part", "[", "0", "]", "=", "part", "[", "0", "]", ".", "chr", ".", "upcase", "}", ".", "join", "end" ]
Given a word with dashes, returns a camel cased version of it. @example classify('job-name') # => 'JobName'
[ "Given", "a", "word", "with", "dashes", "returns", "a", "camel", "cased", "version", "of", "it", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L25-L27
19,479
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.dasherize
def dasherize(word) classify(word).to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("_", "-").downcase end
ruby
def dasherize(word) classify(word).to_s.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("_", "-").downcase end
[ "def", "dasherize", "(", "word", ")", "classify", "(", "word", ")", ".", "to_s", ".", "gsub", "(", "/", "/", ",", "'/'", ")", ".", "gsub", "(", "/", "/", ",", "'\\1_\\2'", ")", ".", "gsub", "(", "/", "\\d", "/", ",", "'\\1_\\2'", ")", ".", "tr", "(", "\"_\"", ",", "\"-\"", ")", ".", "downcase", "end" ]
Given a class, dasherizes the name, used for getting tube names @example dasherize('JobName') # => "job-name"
[ "Given", "a", "class", "dasherizes", "the", "name", "used", "for", "getting", "tube", "names" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L34-L39
19,480
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.resolve_priority
def resolve_priority(pri) if pri.respond_to?(:queue_priority) resolve_priority(pri.queue_priority) elsif pri.is_a?(String) || pri.is_a?(Symbol) # named priority resolve_priority(Backburner.configuration.priority_labels[pri.to_sym]) elsif pri.is_a?(Integer) # numerical pri else # default Backburner.configuration.default_priority end end
ruby
def resolve_priority(pri) if pri.respond_to?(:queue_priority) resolve_priority(pri.queue_priority) elsif pri.is_a?(String) || pri.is_a?(Symbol) # named priority resolve_priority(Backburner.configuration.priority_labels[pri.to_sym]) elsif pri.is_a?(Integer) # numerical pri else # default Backburner.configuration.default_priority end end
[ "def", "resolve_priority", "(", "pri", ")", "if", "pri", ".", "respond_to?", "(", ":queue_priority", ")", "resolve_priority", "(", "pri", ".", "queue_priority", ")", "elsif", "pri", ".", "is_a?", "(", "String", ")", "||", "pri", ".", "is_a?", "(", "Symbol", ")", "# named priority", "resolve_priority", "(", "Backburner", ".", "configuration", ".", "priority_labels", "[", "pri", ".", "to_sym", "]", ")", "elsif", "pri", ".", "is_a?", "(", "Integer", ")", "# numerical", "pri", "else", "# default", "Backburner", ".", "configuration", ".", "default_priority", "end", "end" ]
Resolves job priority based on the value given. Can be integer, a class or nothing @example resolve_priority(1000) => 1000 resolve_priority(FooBar) => <queue priority> resolve_priority(nil) => <default priority>
[ "Resolves", "job", "priority", "based", "on", "the", "value", "given", ".", "Can", "be", "integer", "a", "class", "or", "nothing" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L112-L122
19,481
nesquena/backburner
lib/backburner/helpers.rb
Backburner.Helpers.resolve_respond_timeout
def resolve_respond_timeout(ttr) if ttr.respond_to?(:queue_respond_timeout) resolve_respond_timeout(ttr.queue_respond_timeout) elsif ttr.is_a?(Integer) # numerical ttr else # default Backburner.configuration.respond_timeout end end
ruby
def resolve_respond_timeout(ttr) if ttr.respond_to?(:queue_respond_timeout) resolve_respond_timeout(ttr.queue_respond_timeout) elsif ttr.is_a?(Integer) # numerical ttr else # default Backburner.configuration.respond_timeout end end
[ "def", "resolve_respond_timeout", "(", "ttr", ")", "if", "ttr", ".", "respond_to?", "(", ":queue_respond_timeout", ")", "resolve_respond_timeout", "(", "ttr", ".", "queue_respond_timeout", ")", "elsif", "ttr", ".", "is_a?", "(", "Integer", ")", "# numerical", "ttr", "else", "# default", "Backburner", ".", "configuration", ".", "respond_timeout", "end", "end" ]
Resolves job respond timeout based on the value given. Can be integer, a class or nothing @example resolve_respond_timeout(1000) => 1000 resolve_respond_timeout(FooBar) => <queue respond_timeout> resolve_respond_timeout(nil) => <default respond_timeout>
[ "Resolves", "job", "respond", "timeout", "based", "on", "the", "value", "given", ".", "Can", "be", "integer", "a", "class", "or", "nothing" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/helpers.rb#L131-L139
19,482
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.work_one_job
def work_one_job(conn = connection) begin job = reserve_job(conn) rescue Beaneater::TimedOutError => e return end self.log_job_begin(job.name, job.args) job.process self.log_job_end(job.name) rescue Backburner::Job::JobFormatInvalid => e self.log_error self.exception_message(e) rescue => e # Error occurred processing job self.log_error self.exception_message(e) unless e.is_a?(Backburner::Job::RetryJob) unless job self.log_error "Error occurred before we were able to assign a job. Giving up without retrying!" return end # NB: There's a slight chance here that the connection to beanstalkd has # gone down between the time we reserved / processed the job and here. num_retries = job.stats.releases retry_status = "failed: attempt #{num_retries+1} of #{queue_config.max_job_retries+1}" if num_retries < queue_config.max_job_retries # retry again delay = queue_config.retry_delay_proc.call(queue_config.retry_delay, num_retries) rescue queue_config.retry_delay job.retry(num_retries + 1, delay) self.log_job_end(job.name, "#{retry_status}, retrying in #{delay}s") if job_started_at else # retries failed, bury job.bury self.log_job_end(job.name, "#{retry_status}, burying") if job_started_at end handle_error(e, job.name, job.args, job) end
ruby
def work_one_job(conn = connection) begin job = reserve_job(conn) rescue Beaneater::TimedOutError => e return end self.log_job_begin(job.name, job.args) job.process self.log_job_end(job.name) rescue Backburner::Job::JobFormatInvalid => e self.log_error self.exception_message(e) rescue => e # Error occurred processing job self.log_error self.exception_message(e) unless e.is_a?(Backburner::Job::RetryJob) unless job self.log_error "Error occurred before we were able to assign a job. Giving up without retrying!" return end # NB: There's a slight chance here that the connection to beanstalkd has # gone down between the time we reserved / processed the job and here. num_retries = job.stats.releases retry_status = "failed: attempt #{num_retries+1} of #{queue_config.max_job_retries+1}" if num_retries < queue_config.max_job_retries # retry again delay = queue_config.retry_delay_proc.call(queue_config.retry_delay, num_retries) rescue queue_config.retry_delay job.retry(num_retries + 1, delay) self.log_job_end(job.name, "#{retry_status}, retrying in #{delay}s") if job_started_at else # retries failed, bury job.bury self.log_job_end(job.name, "#{retry_status}, burying") if job_started_at end handle_error(e, job.name, job.args, job) end
[ "def", "work_one_job", "(", "conn", "=", "connection", ")", "begin", "job", "=", "reserve_job", "(", "conn", ")", "rescue", "Beaneater", "::", "TimedOutError", "=>", "e", "return", "end", "self", ".", "log_job_begin", "(", "job", ".", "name", ",", "job", ".", "args", ")", "job", ".", "process", "self", ".", "log_job_end", "(", "job", ".", "name", ")", "rescue", "Backburner", "::", "Job", "::", "JobFormatInvalid", "=>", "e", "self", ".", "log_error", "self", ".", "exception_message", "(", "e", ")", "rescue", "=>", "e", "# Error occurred processing job", "self", ".", "log_error", "self", ".", "exception_message", "(", "e", ")", "unless", "e", ".", "is_a?", "(", "Backburner", "::", "Job", "::", "RetryJob", ")", "unless", "job", "self", ".", "log_error", "\"Error occurred before we were able to assign a job. Giving up without retrying!\"", "return", "end", "# NB: There's a slight chance here that the connection to beanstalkd has", "# gone down between the time we reserved / processed the job and here.", "num_retries", "=", "job", ".", "stats", ".", "releases", "retry_status", "=", "\"failed: attempt #{num_retries+1} of #{queue_config.max_job_retries+1}\"", "if", "num_retries", "<", "queue_config", ".", "max_job_retries", "# retry again", "delay", "=", "queue_config", ".", "retry_delay_proc", ".", "call", "(", "queue_config", ".", "retry_delay", ",", "num_retries", ")", "rescue", "queue_config", ".", "retry_delay", "job", ".", "retry", "(", "num_retries", "+", "1", ",", "delay", ")", "self", ".", "log_job_end", "(", "job", ".", "name", ",", "\"#{retry_status}, retrying in #{delay}s\"", ")", "if", "job_started_at", "else", "# retries failed, bury", "job", ".", "bury", "self", ".", "log_job_end", "(", "job", ".", "name", ",", "\"#{retry_status}, burying\"", ")", "if", "job_started_at", "end", "handle_error", "(", "e", ",", "job", ".", "name", ",", "job", ".", "args", ",", "job", ")", "end" ]
Performs a job by reserving a job from beanstalk and processing it @example @worker.work_one_job @raise [Beaneater::NotConnected] If beanstalk fails to connect multiple times.
[ "Performs", "a", "job", "by", "reserving", "a", "job", "from", "beanstalk", "and", "processing", "it" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L129-L164
19,483
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.new_connection
def new_connection Connection.new(Backburner.configuration.beanstalk_url) { |conn| Backburner::Hooks.invoke_hook_events(self, :on_reconnect, conn) } end
ruby
def new_connection Connection.new(Backburner.configuration.beanstalk_url) { |conn| Backburner::Hooks.invoke_hook_events(self, :on_reconnect, conn) } end
[ "def", "new_connection", "Connection", ".", "new", "(", "Backburner", ".", "configuration", ".", "beanstalk_url", ")", "{", "|", "conn", "|", "Backburner", "::", "Hooks", ".", "invoke_hook_events", "(", "self", ",", ":on_reconnect", ",", "conn", ")", "}", "end" ]
Return a new connection instance
[ "Return", "a", "new", "connection", "instance" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L170-L172
19,484
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.reserve_job
def reserve_job(conn, reserve_timeout = Backburner.configuration.reserve_timeout) Backburner::Job.new(conn.tubes.reserve(reserve_timeout)) end
ruby
def reserve_job(conn, reserve_timeout = Backburner.configuration.reserve_timeout) Backburner::Job.new(conn.tubes.reserve(reserve_timeout)) end
[ "def", "reserve_job", "(", "conn", ",", "reserve_timeout", "=", "Backburner", ".", "configuration", ".", "reserve_timeout", ")", "Backburner", "::", "Job", ".", "new", "(", "conn", ".", "tubes", ".", "reserve", "(", "reserve_timeout", ")", ")", "end" ]
Reserve a job from the watched queues
[ "Reserve", "a", "job", "from", "the", "watched", "queues" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L175-L177
19,485
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.handle_error
def handle_error(e, name, args, job) if error_handler = Backburner.configuration.on_error if error_handler.arity == 1 error_handler.call(e) elsif error_handler.arity == 3 error_handler.call(e, name, args) else error_handler.call(e, name, args, job) end end end
ruby
def handle_error(e, name, args, job) if error_handler = Backburner.configuration.on_error if error_handler.arity == 1 error_handler.call(e) elsif error_handler.arity == 3 error_handler.call(e, name, args) else error_handler.call(e, name, args, job) end end end
[ "def", "handle_error", "(", "e", ",", "name", ",", "args", ",", "job", ")", "if", "error_handler", "=", "Backburner", ".", "configuration", ".", "on_error", "if", "error_handler", ".", "arity", "==", "1", "error_handler", ".", "call", "(", "e", ")", "elsif", "error_handler", ".", "arity", "==", "3", "error_handler", ".", "call", "(", "e", ",", "name", ",", "args", ")", "else", "error_handler", ".", "call", "(", "e", ",", "name", ",", "args", ",", "job", ")", "end", "end", "end" ]
Handles an error according to custom definition Used when processing a job that errors out
[ "Handles", "an", "error", "according", "to", "custom", "definition", "Used", "when", "processing", "a", "job", "that", "errors", "out" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L190-L200
19,486
nesquena/backburner
lib/backburner/worker.rb
Backburner.Worker.compact_tube_names
def compact_tube_names(tube_names) tube_names = tube_names.first if tube_names && tube_names.size == 1 && tube_names.first.is_a?(Array) tube_names = Array(tube_names).compact if tube_names && Array(tube_names).compact.size > 0 tube_names = nil if tube_names && tube_names.compact.empty? tube_names ||= Backburner.default_queues.any? ? Backburner.default_queues : all_existing_queues Array(tube_names).uniq end
ruby
def compact_tube_names(tube_names) tube_names = tube_names.first if tube_names && tube_names.size == 1 && tube_names.first.is_a?(Array) tube_names = Array(tube_names).compact if tube_names && Array(tube_names).compact.size > 0 tube_names = nil if tube_names && tube_names.compact.empty? tube_names ||= Backburner.default_queues.any? ? Backburner.default_queues : all_existing_queues Array(tube_names).uniq end
[ "def", "compact_tube_names", "(", "tube_names", ")", "tube_names", "=", "tube_names", ".", "first", "if", "tube_names", "&&", "tube_names", ".", "size", "==", "1", "&&", "tube_names", ".", "first", ".", "is_a?", "(", "Array", ")", "tube_names", "=", "Array", "(", "tube_names", ")", ".", "compact", "if", "tube_names", "&&", "Array", "(", "tube_names", ")", ".", "compact", ".", "size", ">", "0", "tube_names", "=", "nil", "if", "tube_names", "&&", "tube_names", ".", "compact", ".", "empty?", "tube_names", "||=", "Backburner", ".", "default_queues", ".", "any?", "?", "Backburner", ".", "default_queues", ":", "all_existing_queues", "Array", "(", "tube_names", ")", ".", "uniq", "end" ]
Normalizes tube names given array of tube_names Compacts nil items, flattens arrays, sets tubes to nil if no valid names Loads default tubes when no tubes given.
[ "Normalizes", "tube", "names", "given", "array", "of", "tube_names", "Compacts", "nil", "items", "flattens", "arrays", "sets", "tubes", "to", "nil", "if", "no", "valid", "names", "Loads", "default", "tubes", "when", "no", "tubes", "given", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/worker.rb#L205-L211
19,487
nesquena/backburner
lib/backburner/logger.rb
Backburner.Logger.log_job_end
def log_job_end(name, message = nil) ellapsed = Time.now - job_started_at ms = (ellapsed.to_f * 1000).to_i action_word = message ? 'Finished' : 'Completed' log_info("#{action_word} #{name} in #{ms}ms #{message}") end
ruby
def log_job_end(name, message = nil) ellapsed = Time.now - job_started_at ms = (ellapsed.to_f * 1000).to_i action_word = message ? 'Finished' : 'Completed' log_info("#{action_word} #{name} in #{ms}ms #{message}") end
[ "def", "log_job_end", "(", "name", ",", "message", "=", "nil", ")", "ellapsed", "=", "Time", ".", "now", "-", "job_started_at", "ms", "=", "(", "ellapsed", ".", "to_f", "*", "1000", ")", ".", "to_i", "action_word", "=", "message", "?", "'Finished'", ":", "'Completed'", "log_info", "(", "\"#{action_word} #{name} in #{ms}ms #{message}\"", ")", "end" ]
Print out when a job completed If message is nil, job is considered complete
[ "Print", "out", "when", "a", "job", "completed", "If", "message", "is", "nil", "job", "is", "considered", "complete" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/logger.rb#L18-L23
19,488
nesquena/backburner
lib/backburner/job.rb
Backburner.Job.process
def process # Invoke before hook and stop if false res = @hooks.invoke_hook_events(job_name, :before_perform, *args) return false unless res # Execute the job @hooks.around_hook_events(job_name, :around_perform, *args) do # We subtract one to ensure we timeout before beanstalkd does, except if: # a) ttr == 0, to support never timing out # b) ttr == 1, so that we don't accidentally set it to never time out # NB: A ttr of 1 will likely result in race conditions between # Backburner and beanstalkd and should probably be avoided timeout_job_after(task.ttr > 1 ? task.ttr - 1 : task.ttr) { job_class.perform(*args) } end task.delete # Invoke after perform hook @hooks.invoke_hook_events(job_name, :after_perform, *args) rescue => e @hooks.invoke_hook_events(job_name, :on_failure, e, *args) raise e end
ruby
def process # Invoke before hook and stop if false res = @hooks.invoke_hook_events(job_name, :before_perform, *args) return false unless res # Execute the job @hooks.around_hook_events(job_name, :around_perform, *args) do # We subtract one to ensure we timeout before beanstalkd does, except if: # a) ttr == 0, to support never timing out # b) ttr == 1, so that we don't accidentally set it to never time out # NB: A ttr of 1 will likely result in race conditions between # Backburner and beanstalkd and should probably be avoided timeout_job_after(task.ttr > 1 ? task.ttr - 1 : task.ttr) { job_class.perform(*args) } end task.delete # Invoke after perform hook @hooks.invoke_hook_events(job_name, :after_perform, *args) rescue => e @hooks.invoke_hook_events(job_name, :on_failure, e, *args) raise e end
[ "def", "process", "# Invoke before hook and stop if false", "res", "=", "@hooks", ".", "invoke_hook_events", "(", "job_name", ",", ":before_perform", ",", "args", ")", "return", "false", "unless", "res", "# Execute the job", "@hooks", ".", "around_hook_events", "(", "job_name", ",", ":around_perform", ",", "args", ")", "do", "# We subtract one to ensure we timeout before beanstalkd does, except if:", "# a) ttr == 0, to support never timing out", "# b) ttr == 1, so that we don't accidentally set it to never time out", "# NB: A ttr of 1 will likely result in race conditions between", "# Backburner and beanstalkd and should probably be avoided", "timeout_job_after", "(", "task", ".", "ttr", ">", "1", "?", "task", ".", "ttr", "-", "1", ":", "task", ".", "ttr", ")", "{", "job_class", ".", "perform", "(", "args", ")", "}", "end", "task", ".", "delete", "# Invoke after perform hook", "@hooks", ".", "invoke_hook_events", "(", "job_name", ",", ":after_perform", ",", "args", ")", "rescue", "=>", "e", "@hooks", ".", "invoke_hook_events", "(", "job_name", ",", ":on_failure", ",", "e", ",", "args", ")", "raise", "e", "end" ]
Processes a job and handles any failure, deleting the job once complete @example @task.process
[ "Processes", "a", "job", "and", "handles", "any", "failure", "deleting", "the", "job", "once", "complete" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/job.rb#L45-L64
19,489
nesquena/backburner
lib/backburner/job.rb
Backburner.Job.timeout_job_after
def timeout_job_after(secs, &block) begin Timeout::timeout(secs) { yield } rescue Timeout::Error => e raise JobTimeout, "#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\nbacktrace: #{e.backtrace}" end end
ruby
def timeout_job_after(secs, &block) begin Timeout::timeout(secs) { yield } rescue Timeout::Error => e raise JobTimeout, "#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\nbacktrace: #{e.backtrace}" end end
[ "def", "timeout_job_after", "(", "secs", ",", "&", "block", ")", "begin", "Timeout", "::", "timeout", "(", "secs", ")", "{", "yield", "}", "rescue", "Timeout", "::", "Error", "=>", "e", "raise", "JobTimeout", ",", "\"#{name}(#{(@args||[]).join(', ')}) hit #{secs}s timeout.\\nbacktrace: #{e.backtrace}\"", "end", "end" ]
Timeout job within specified block after given time. @example timeout_job_after(3) { do_something! }
[ "Timeout", "job", "within", "specified", "block", "after", "given", "time", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/job.rb#L109-L115
19,490
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.retryable
def retryable(options = {}, &block) options = {:max_retries => 4, :on_retry => nil, :retry_delay => 1.0}.merge!(options) retry_count = options[:max_retries] begin yield rescue Beaneater::NotConnected if retry_count > 0 reconnect! retry_count -= 1 sleep options[:retry_delay] options[:on_retry].call if options[:on_retry].respond_to?(:call) retry else # stop retrying raise e end end end
ruby
def retryable(options = {}, &block) options = {:max_retries => 4, :on_retry => nil, :retry_delay => 1.0}.merge!(options) retry_count = options[:max_retries] begin yield rescue Beaneater::NotConnected if retry_count > 0 reconnect! retry_count -= 1 sleep options[:retry_delay] options[:on_retry].call if options[:on_retry].respond_to?(:call) retry else # stop retrying raise e end end end
[ "def", "retryable", "(", "options", "=", "{", "}", ",", "&", "block", ")", "options", "=", "{", ":max_retries", "=>", "4", ",", ":on_retry", "=>", "nil", ",", ":retry_delay", "=>", "1.0", "}", ".", "merge!", "(", "options", ")", "retry_count", "=", "options", "[", ":max_retries", "]", "begin", "yield", "rescue", "Beaneater", "::", "NotConnected", "if", "retry_count", ">", "0", "reconnect!", "retry_count", "-=", "1", "sleep", "options", "[", ":retry_delay", "]", "options", "[", ":on_retry", "]", ".", "call", "if", "options", "[", ":on_retry", "]", ".", "respond_to?", "(", ":call", ")", "retry", "else", "# stop retrying", "raise", "e", "end", "end", "end" ]
Yield to a block that will be retried several times if the connection to beanstalk goes down and is able to be re-established. @param options Hash Options. Valid options are: :max_retries Integer The maximum number of times the block will be yielded to. Defaults to 4 :on_retry Proc An optional proc that will be called for each retry. Will be called after the connection is re-established and :retry_delay has passed but before the block is yielded to again :retry_delay Float The amount to sleep before retrying. Defaults to 1.0 @raise Beaneater::NotConnected If a connection is unable to be re-established
[ "Yield", "to", "a", "block", "that", "will", "be", "retried", "several", "times", "if", "the", "connection", "to", "beanstalk", "goes", "down", "and", "is", "able", "to", "be", "re", "-", "established", "." ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L63-L81
19,491
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.ensure_connected!
def ensure_connected!(max_retries = 4, retry_delay = 1.0) return self if connected? begin reconnect! return self rescue Beaneater::NotConnected => e if max_retries > 0 max_retries -= 1 sleep retry_delay retry else # stop retrying raise e end end end
ruby
def ensure_connected!(max_retries = 4, retry_delay = 1.0) return self if connected? begin reconnect! return self rescue Beaneater::NotConnected => e if max_retries > 0 max_retries -= 1 sleep retry_delay retry else # stop retrying raise e end end end
[ "def", "ensure_connected!", "(", "max_retries", "=", "4", ",", "retry_delay", "=", "1.0", ")", "return", "self", "if", "connected?", "begin", "reconnect!", "return", "self", "rescue", "Beaneater", "::", "NotConnected", "=>", "e", "if", "max_retries", ">", "0", "max_retries", "-=", "1", "sleep", "retry_delay", "retry", "else", "# stop retrying", "raise", "e", "end", "end", "end" ]
Attempts to ensure a connection to beanstalk is established but only if we're not connected already @param max_retries Integer The maximum number of times to attempt connecting. Defaults to 4 @param retry_delay Float The time to wait between retrying to connect. Defaults to 1.0 @raise [Beaneater::NotConnected] If beanstalk fails to connect after multiple attempts. @return Connection This Connection is returned if the connection to beanstalk is open or was able to be reconnected
[ "Attempts", "to", "ensure", "a", "connection", "to", "beanstalk", "is", "established", "but", "only", "if", "we", "re", "not", "connected", "already" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L107-L123
19,492
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.beanstalk_addresses
def beanstalk_addresses uri = self.url.is_a?(Array) ? self.url.first : self.url beanstalk_host_and_port(uri) end
ruby
def beanstalk_addresses uri = self.url.is_a?(Array) ? self.url.first : self.url beanstalk_host_and_port(uri) end
[ "def", "beanstalk_addresses", "uri", "=", "self", ".", "url", ".", "is_a?", "(", "Array", ")", "?", "self", ".", "url", ".", "first", ":", "self", ".", "url", "beanstalk_host_and_port", "(", "uri", ")", "end" ]
Returns the beanstalk queue addresses @example beanstalk_addresses => ["127.0.0.1:11300"]
[ "Returns", "the", "beanstalk", "queue", "addresses" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L130-L133
19,493
nesquena/backburner
lib/backburner/connection.rb
Backburner.Connection.beanstalk_host_and_port
def beanstalk_host_and_port(uri_string) uri = URI.parse(uri_string) raise(BadURL, uri_string) if uri.scheme != 'beanstalk'.freeze "#{uri.host}:#{uri.port || 11300}" end
ruby
def beanstalk_host_and_port(uri_string) uri = URI.parse(uri_string) raise(BadURL, uri_string) if uri.scheme != 'beanstalk'.freeze "#{uri.host}:#{uri.port || 11300}" end
[ "def", "beanstalk_host_and_port", "(", "uri_string", ")", "uri", "=", "URI", ".", "parse", "(", "uri_string", ")", "raise", "(", "BadURL", ",", "uri_string", ")", "if", "uri", ".", "scheme", "!=", "'beanstalk'", ".", "freeze", "\"#{uri.host}:#{uri.port || 11300}\"", "end" ]
Returns a host and port based on the uri_string given @example beanstalk_host_and_port("beanstalk://127.0.0.1") => "127.0.0.1:11300"
[ "Returns", "a", "host", "and", "port", "based", "on", "the", "uri_string", "given" ]
ea2086ba37fa3cbf153a0dd3a8820dc634502510
https://github.com/nesquena/backburner/blob/ea2086ba37fa3cbf153a0dd3a8820dc634502510/lib/backburner/connection.rb#L140-L144
19,494
arvindvyas/Country-State-Select
app/controllers/country_state_select/cscs_controller.rb
CountryStateSelect.CscsController.find_cities
def find_cities cities = CS.cities(params[:state_id].to_sym, params[:country_id].to_sym) respond_to do |format| format.json { render :json => cities.to_a} end end
ruby
def find_cities cities = CS.cities(params[:state_id].to_sym, params[:country_id].to_sym) respond_to do |format| format.json { render :json => cities.to_a} end end
[ "def", "find_cities", "cities", "=", "CS", ".", "cities", "(", "params", "[", ":state_id", "]", ".", "to_sym", ",", "params", "[", ":country_id", "]", ".", "to_sym", ")", "respond_to", "do", "|", "format", "|", "format", ".", "json", "{", "render", ":json", "=>", "cities", ".", "to_a", "}", "end", "end" ]
Sent it to state_id and country id it will return cities of that states
[ "Sent", "it", "to", "state_id", "and", "country", "id", "it", "will", "return", "cities", "of", "that", "states" ]
2c91757ccebe3d1a335a87cf5da1c8241ac38437
https://github.com/arvindvyas/Country-State-Select/blob/2c91757ccebe3d1a335a87cf5da1c8241ac38437/app/controllers/country_state_select/cscs_controller.rb#L13-L19
19,495
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.file_field
def file_field(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) return super if bootstrap.disabled draw_form_group(bootstrap, method, options) do if bootstrap.custom_control content_tag(:div, class: "custom-file") do add_css_class!(options, "custom-file-input") remove_css_class!(options, "form-control") label_text = options.delete(:placeholder) concat super(method, options) label_options = { class: "custom-file-label" } label_options[:for] = options[:id] if options[:id].present? concat label(method, label_text, label_options) end else super(method, options) end end end
ruby
def file_field(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) return super if bootstrap.disabled draw_form_group(bootstrap, method, options) do if bootstrap.custom_control content_tag(:div, class: "custom-file") do add_css_class!(options, "custom-file-input") remove_css_class!(options, "form-control") label_text = options.delete(:placeholder) concat super(method, options) label_options = { class: "custom-file-label" } label_options[:for] = options[:id] if options[:id].present? concat label(method, label_text, label_options) end else super(method, options) end end end
[ "def", "file_field", "(", "method", ",", "options", "=", "{", "}", ")", "bootstrap", "=", "form_bootstrap", ".", "scoped", "(", "options", ".", "delete", "(", ":bootstrap", ")", ")", "return", "super", "if", "bootstrap", ".", "disabled", "draw_form_group", "(", "bootstrap", ",", "method", ",", "options", ")", "do", "if", "bootstrap", ".", "custom_control", "content_tag", "(", ":div", ",", "class", ":", "\"custom-file\"", ")", "do", "add_css_class!", "(", "options", ",", "\"custom-file-input\"", ")", "remove_css_class!", "(", "options", ",", "\"form-control\"", ")", "label_text", "=", "options", ".", "delete", "(", ":placeholder", ")", "concat", "super", "(", "method", ",", "options", ")", "label_options", "=", "{", "class", ":", "\"custom-file-label\"", "}", "label_options", "[", ":for", "]", "=", "options", "[", ":id", "]", "if", "options", "[", ":id", "]", ".", "present?", "concat", "label", "(", "method", ",", "label_text", ",", "label_options", ")", "end", "else", "super", "(", "method", ",", "options", ")", "end", "end", "end" ]
Wrapper for file_field helper. It can accept `custom_control` option. file_field :photo, bootstrap: {custom_control: true}
[ "Wrapper", "for", "file_field", "helper", ".", "It", "can", "accept", "custom_control", "option", "." ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L89-L109
19,496
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.plaintext
def plaintext(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) draw_form_group(bootstrap, method, options) do remove_css_class!(options, "form-control") add_css_class!(options, "form-control-plaintext") options[:readonly] = true ActionView::Helpers::FormBuilder.instance_method(:text_field).bind(self).call(method, options) end end
ruby
def plaintext(method, options = {}) bootstrap = form_bootstrap.scoped(options.delete(:bootstrap)) draw_form_group(bootstrap, method, options) do remove_css_class!(options, "form-control") add_css_class!(options, "form-control-plaintext") options[:readonly] = true ActionView::Helpers::FormBuilder.instance_method(:text_field).bind(self).call(method, options) end end
[ "def", "plaintext", "(", "method", ",", "options", "=", "{", "}", ")", "bootstrap", "=", "form_bootstrap", ".", "scoped", "(", "options", ".", "delete", "(", ":bootstrap", ")", ")", "draw_form_group", "(", "bootstrap", ",", "method", ",", "options", ")", "do", "remove_css_class!", "(", "options", ",", "\"form-control\"", ")", "add_css_class!", "(", "options", ",", "\"form-control-plaintext\"", ")", "options", "[", ":readonly", "]", "=", "true", "ActionView", "::", "Helpers", "::", "FormBuilder", ".", "instance_method", "(", ":text_field", ")", ".", "bind", "(", "self", ")", ".", "call", "(", "method", ",", "options", ")", "end", "end" ]
Bootstrap wrapper for readonly text field that is shown as plain text. plaintext(:value)
[ "Bootstrap", "wrapper", "for", "readonly", "text", "field", "that", "is", "shown", "as", "plain", "text", "." ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L204-L212
19,497
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.primary
def primary(value = nil, options = {}, &block) add_css_class!(options, "btn-primary") submit(value, options, &block) end
ruby
def primary(value = nil, options = {}, &block) add_css_class!(options, "btn-primary") submit(value, options, &block) end
[ "def", "primary", "(", "value", "=", "nil", ",", "options", "=", "{", "}", ",", "&", "block", ")", "add_css_class!", "(", "options", ",", "\"btn-primary\"", ")", "submit", "(", "value", ",", "options", ",", "block", ")", "end" ]
Same as submit button, only with btn-primary class added
[ "Same", "as", "submit", "button", "only", "with", "btn", "-", "primary", "class", "added" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L250-L253
19,498
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.draw_form_group
def draw_form_group(bootstrap, method, options) label = draw_label(bootstrap, method, for_attr: options[:id]) errors = draw_errors(method) control = draw_control(bootstrap, errors, method, options) do yield end form_group_class = "form-group" form_group_class += " row" if bootstrap.horizontal? form_group_class += " mr-sm-2" if bootstrap.inline? content_tag(:div, class: form_group_class) do concat label concat control end end
ruby
def draw_form_group(bootstrap, method, options) label = draw_label(bootstrap, method, for_attr: options[:id]) errors = draw_errors(method) control = draw_control(bootstrap, errors, method, options) do yield end form_group_class = "form-group" form_group_class += " row" if bootstrap.horizontal? form_group_class += " mr-sm-2" if bootstrap.inline? content_tag(:div, class: form_group_class) do concat label concat control end end
[ "def", "draw_form_group", "(", "bootstrap", ",", "method", ",", "options", ")", "label", "=", "draw_label", "(", "bootstrap", ",", "method", ",", "for_attr", ":", "options", "[", ":id", "]", ")", "errors", "=", "draw_errors", "(", "method", ")", "control", "=", "draw_control", "(", "bootstrap", ",", "errors", ",", "method", ",", "options", ")", "do", "yield", "end", "form_group_class", "=", "\"form-group\"", "form_group_class", "+=", "\" row\"", "if", "bootstrap", ".", "horizontal?", "form_group_class", "+=", "\" mr-sm-2\"", "if", "bootstrap", ".", "inline?", "content_tag", "(", ":div", ",", "class", ":", "form_group_class", ")", "do", "concat", "label", "concat", "control", "end", "end" ]
form group wrapper for input fields
[ "form", "group", "wrapper", "for", "input", "fields" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L297-L313
19,499
comfy/comfy-bootstrap-form
lib/comfy_bootstrap_form/form_builder.rb
ComfyBootstrapForm.FormBuilder.draw_control
def draw_control(bootstrap, errors, _method, options) add_css_class!(options, "form-control") add_css_class!(options, "is-invalid") if errors.present? draw_control_column(bootstrap, offset: bootstrap.label[:hide]) do draw_input_group(bootstrap, errors) do yield end end end
ruby
def draw_control(bootstrap, errors, _method, options) add_css_class!(options, "form-control") add_css_class!(options, "is-invalid") if errors.present? draw_control_column(bootstrap, offset: bootstrap.label[:hide]) do draw_input_group(bootstrap, errors) do yield end end end
[ "def", "draw_control", "(", "bootstrap", ",", "errors", ",", "_method", ",", "options", ")", "add_css_class!", "(", "options", ",", "\"form-control\"", ")", "add_css_class!", "(", "options", ",", "\"is-invalid\"", ")", "if", "errors", ".", "present?", "draw_control_column", "(", "bootstrap", ",", "offset", ":", "bootstrap", ".", "label", "[", ":hide", "]", ")", "do", "draw_input_group", "(", "bootstrap", ",", "errors", ")", "do", "yield", "end", "end", "end" ]
Renders control for a given field
[ "Renders", "control", "for", "a", "given", "field" ]
461d5cbd552469eb95e35fbcbed03d13ec702ef7
https://github.com/comfy/comfy-bootstrap-form/blob/461d5cbd552469eb95e35fbcbed03d13ec702ef7/lib/comfy_bootstrap_form/form_builder.rb#L357-L366