CombinedText stringlengths 4 3.42M |
|---|
module EnjuMessage
VERSION = "0.0.10"
end
bumped version
module EnjuMessage
VERSION = "0.0.11"
end
|
require_relative 'member'
class Essbase
# Represents an Essbase dimension, and holds a set of {Member} objects
# representing the members in a dimension.
#
# To obtain a Dimension instance, use the {Cube#[] Cube#[]} method.
class Dimension < Base
include Enumerable
# The {Cube} to which this dimension belongs
attr_reader :cube
# @return [String] the name of the dimension.
attr_reader :name
# @return [String] the storage type: Dense or Sparse.
attr_reader :storage_type
# @return the dimension tag: Accounts, Time, Attribute, etc.
attr_reader :tag
# @!visibility private
#
# Creates a new Dimension object, populated from the supplied IEssDimension
# object.
#
# @param cube [Cube] The cube to which this dimension belongs,
# @param ess_dim [IEssDimension] The JAPI IEssDimension object this class
# is to wrap.
def initialize(cube, ess_dim)
super(cube.log)
@name = ess_dim.name
@storage_type = ess_dim.storage_type.to_s
@tag = ess_dim.tag.to_s
@cube = cube
@root_member = nil
end
# @return [Boolean] true if this dimension is dense, false if it is not.
def dense?
@storage_type == 'Dense'
end
# @return [Boolean] true if this dimension is sparse or an attribute
# dimension.
def sparse?
@storage_type == 'Sparse' && !(@tag =~ /^Attr/)
end
# @return [Boolean] true if this dimension is an attribute dimension,
# false otherwise.
def attribute_dimension?
@storage_type == 'Sparse' && (@tag =~ /^Attr/)
end
# @return [Boolean] true unless this dimension is an attribute dimension.
def non_attribute_dimension?
!attribute_dimension?
end
# @return [Member] The top-most member in the dimension (i.e. the member
# with the same name as the dimension).
def root_member
retrieve_members unless @members
@root_member
end
# Returns a {Member} object containing details about the dimension member
# +mbr_name+.
#
# @param mbr_name [String] A name or alias for the member to be returned.
# An Essbase substitution variable can also be passed, in which case
# the variable value is retrieved, and the corresponding {Member} object
# returned.
#
# @return [Member] if the named member was found in this dimension.
# @return [NilClass] if no matching member can be found.
def [](mbr_name)
retrieve_members unless @members
case mbr_name
when /^['"\[]?&(.+?)['"\]]?$/
# Substitution variable
mbr_name = @cube.get_substitution_variable_value($1)
when /^['"\[]?(.+?)['"\]]?$/
# Quoted
mbr_name = $1
end
mbr = @member_lookup[mbr_name.upcase]
unless mbr
# Search by alias
@cube.get_alias_table_names.each do |tbl|
mbr = @members.find{ |mbr| (al = mbr.alias(tbl)) &&
(al.upcase == mbr_name.upcase) }
break if mbr
end
end
mbr
end
# Takes a +mbr_spec+ and expands it into an Array of matching Member
# objects.
#
# Member names may be followed by various macros indicating relations of
# the member to return, or alternatively, an Essbase calc function may be
# used to query the outline for matching members.
#
# Relationship macros cause a member to be replaced by an expansion set
# of members that have that relationship to the member. A macro is specified
# by the addition of a +.<Relation>+ suffix, e.g. <Member>.Children.
# Additionally, the relationship in question may be further qualified by +I+
# and/or +R+ modifiers, where +I+ means include the member itself in the
# expansion set, and +R+ means consider all hierarchies when expanding the
# member.
#
# The following relationship macros are supported:
# - +.Parent+ returns the member parent
# - +.[I,R]Ancestors+ returns the member's ancestors
# - +.[I]Children+ returns the member's children; supports the I modifier
# - +.[I,R]Descendants+ returns the member's descendants
# - +.[R]Leaves+ or +.[R]Level0+ returns the leaf/level 0 descendants of
# the member
# - +.[R]Level<N>+ returns the related members at level _N_
# - +.[R]Generation<N>+ returns the related members at generation _N_
# - +.UDA(<uda>)+ returns descendants of the member that have the UDA <uda>
#
# All of the above do not require querying of Essbase, and so are cheap
# to evaluate. Alternatively, Essbase calc functions can be used to express
# more complicated relationships, such as compound relationships.
#
# The +mbr_spec+ can be a single specification (using the macros or calc
# syntax described), or it can an array of specifications, each of which
# is expanded to the corresponding set of member(s). By default, each such
# set of member(s) is appended to the result, but several other possibilities
# are supported, using an optional operation type prefix:
# - :add <spec> or + <spec>: The member set is appended to the results;
# this is the default behaviour when no operation type is specified.
# - :minus <spec> or - <spec>: The resulting member(s) are removed from
# the results. Members in this set that are not in the results are
# ignored.
# - :filter <ruby expr>: The current result set is filtered to only
# include members that satisy <ruby expr>. The results are always
# Member object instances, so the filter expression can use any
# properties of the members to define the filter condition.
# - :map <ruby expor>: The current result set is mapped using <ruby expr>,
# e.g. ":map parent" would convert the results to the parents of the
# members currently in the result set. The result of the :map operation
# should be Member objects.
# - :unique: Removes duplicates from the result set.
#
# @param mbr_spec [Array|String] A string or array of strings containing
# member names, optionally followed by an expansion macro, such as
# .Children, .Leaves, .Descendants, etc
# @return [Array<Member>] An array of Member objects representing the
def expand_members(mbr_spec, options={})
retrieve_members unless @members
mbr_spec = [mbr_spec].flatten
all_mbrs = []
mbr_spec.each do |spec|
spec.strip!
case spec
when /^(?:\-|[:!](?:minus|not)\s)\s*(.+)/
all_mbrs -= process_member_spec($1)
when /^(?:\+|[:!](?:add|or)\s)\s*(.+)/
all_mbrs += process_member_spec($1)
when /^[:!]and\s+(.+)/ # Can't use & as a shortcut, since that identifies a subvar
all_mbrs = all_mbrs & process_member_spec($1)
when /^[:!]filter\s+(.+)/
spec = eval("lambda{ #{$1} }")
all_mbrs.select!{ |mbr| mbr.instance_exec(&spec) }
when /^[:!]map\s+(.+)/
spec = eval("lambda{ #{$1} }")
all_mbrs.map!{ |mbr| mbr.instance_exec(&spec) }.flatten!
when /^[!:]uniq(ue)?\s*$/
all_mbrs.uniq!
else
all_mbrs.concat(process_member_spec(spec))
end
end
if all_mbrs.size == 0 && options.fetch(:raise_if_empty, true)
raise ArgumentError, "Member specification #{mbr_spec} for #{self.name} returned no members"
end
all_mbrs
end
# Takes a +spec+ and expands it into an Array of matching Member objects.
#
# Member names may be followed by various macros indicating relations of
# the member to return, or alternatively, an Essbase calc function may be
# used to query the outline for matching members.
#
# Relationship macros cause a member to be replaced by an expansion set
# of members that have that relationship to the member. A macro is specified
# by the addition of a +.<Relation>+ suffix, e.g. <Member>.Children.
# Additionally, the relationship in question may be further qualified by +I+
# and/or +R+ modifiers, where +I+ means include the member itself in the
# expansion set, and +R+ means consider all hierarchies when expanding the
# member.
#
# The following relationship macros are supported:
# - +.Parent+ returns the member parent
# - +.[I,R]Ancestors+ returns the member's ancestors
# - +.[I]Children+ returns the member's children; supports the I modifier
# - +.[I,R]Descendants+ returns the member's descendants
# - +.[R]Leaves+ or +.[R]Level0+ returns the leaf/level 0 descendants of
# the member
# - +.[R]Level<N>+ returns the related members at level _N_
# - +.[R]Generation<N>+ returns the related members at generation _N_
# - + .[I]Shared returns all other instances of the member
# - +.UDA(<uda>)+ returns descendants of the member that have the UDA <uda>
#
# All of the above do not require querying of Essbase, and so are cheap
# to evaluate. Alternatively, Essbase calc functions can be used to express
# more complicated relationships, such as compound relationships.
def process_member_spec(spec)
case spec.strip
when /^['"\[]?(.+?)['"\]]?\.(Parent|I?Children|I?R?Descendants|I?R?Ancestors|R?Level0|R?Leaves|I?Shared)$/i
# Memer name with expansion macro
mbr = self[$1]
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}' in #{spec}" unless mbr
mthd = $2.downcase
mthd += '_members' if mthd =~ /shared$/
rels = mbr.send(mthd.intern)
mbrs = rels.is_a?(Array) ? rels : [rels]
when /^['"\[]?(.+?)['"\]]?\.(R)?(Level|Generation|Relative)\(?(\d+)\)?$/i
# Memer name with level/generation expansion macro
mbr = self[$1]
sign = $3.downcase == 'level' ? -1 : 1
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}' in #{spec}" unless mbr
mbrs = mbr.relative($4.to_i * sign, !!$2)
when /^['"\[]?(.+?)['"\]]?\.UDA\(['"]?(.+?)['"]?\)$/i
# Memer name with UDA expansion macro
mbr = self[$1]
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}' in #{spec}" unless mbr
mbrs = mbr.idescendants.select{ |mbr| mbr.has_uda?($2) }
when /[@:,]/
# An Essbase calc function or range - execute query and use results to find Member objects
mbrs = []
mbr_sel = try{ @cube.open_member_selection("MemberQuery") }
begin
mbr_sel.execute_query(<<-EOQ.strip, spec)
<OutputType Binary
<SelectMbrInfo(MemberName, ParentMemberName)
EOQ
mbr_sel.get_members && mbr_sel.get_members.get_all.each do |ess_mbr|
mbr = self[ess_mbr.name]
raise ArgumentError, "No member in #{self.name} named '#{ess_mbr.name}'" unless mbr
if mbr.parent && mbr.parent.name != ess_mbr.parent_member_name
mbr = mbr.shared_members.find{ |mbr| mbr.parent.name == ess_mbr.parent_member_name }
raise "Cannot locate #{ess_mbr.name} with parent #{ess_mbr.parent_member_name}" unless mbr
end
mbrs << mbr
end
ensure
mbr_sel.close
end
when /^['"\[]?(.+?)['"\]]?$/
# Plain member name
mbr = self[$1]
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}'" unless mbr
mbrs = [mbr]
else
raise ArgumentError, "Unrecognised #{self.name} member '#{spec}'"
end
end
# Performs a traversal of the dimension hierarchy, yielding each Member
# in the dimension to the supplied block.
#
# @note By default, this iteration of members excludes shared members,
# but if these are desired, specify true in the :include_shared option.
#
# @param opts [Hash] An options hash.
# @option opts [Boolean] :include_shared If true, includes shared members
# when iterating over the dimension. If false (the default), shared
# members are not yielded.
#
# @yield Yields a {Member} object for each member in the dimension.
# @yieldparam mbr [Member] The current member in the iteration.
def each(opts = {})
retrieve_members unless @members
include_shared = opts.fetch(:include_shared, false)
@members.each do |mbr|
yield mbr unless mbr.shared? || include_shared
end
end
# Performs a depth-first traversal of the dimension, yielding members
# to the supplied block. A depth-first traversal yields members in
# outline order.
#
# @yield Yields each member of the dimension as it is visited
# @yieldparam mbr [Member] A member of the dimension
def walk(options = {}, &blk)
retrieve_members unless @members
@root_member.traverse(0, options, &blk)
end
# Retrieves the current set of members for this dimension.
#
# Note: this method is called automatically the first time a member is
# requested from a dimension, and so would not normally need to be called
# directly unless you wish to refresh the dimension members, e.g. after
# a dimension build.
def retrieve_members
@root_member = nil
@members = []
shared = []
@member_lookup = {}
log.finer "Retrieving members of dimension '#{@name}'"
alias_tbls = try{ @cube.get_alias_table_names.to_a }
mbr_sel = try{ @cube.open_member_selection("MemberQuery") }
begin
spec = %Q{@IDESCENDANTS("#{self.name}")}
query = <<-EOQ.strip
<OutputType Binary
<SelectMbrInfo(MemberName, MemberAliasName, ParentMemberName,
MemberGeneration, MemberLevel, Consolidation,
ShareOption, MemberFormula, UDAList)
EOQ
@cube.instrument 'retrieve_members', dimension: self do
try{ mbr_sel.execute_query(query, spec) }
end
mbr_sel.get_members.get_all.each do |ess_mbr|
mbr = Member.new(self, ess_mbr, alias_tbls)
@members << mbr
if mbr.shared?
shared << mbr
else
@member_lookup[mbr.name.upcase] = mbr
end
end
# Link shared members to non-shared member (and vice versa)
shared.each do |smbr|
mbr = @member_lookup[smbr.name.upcase]
smbr.instance_variable_set(:@non_shared_member, mbr)
mbr.instance_variable_get(:@shared_members) << smbr
end
@root_member = @member_lookup[self.name.upcase]
# Convert parent names to references to the parent Member object
# This can only be done after we've seen all members, since the
# member selection query returns parents after children
@members.each do |mbr|
par = @member_lookup[mbr.parent.upcase]
mbr.instance_variable_set(:@parent, par)
par.instance_variable_get(:@children) << mbr if par
end
ensure
try{ mbr_sel.close }
end
log.finer "Retrieved #{@members.size} members"
end
# Returns the name of the dimension
def to_s
@name
end
end
end
Ensure @fn expansions return wrapped IEssMember objects
require_relative 'member'
class Essbase
# Represents an Essbase dimension, and holds a set of {Member} objects
# representing the members in a dimension.
#
# To obtain a Dimension instance, use the {Cube#[] Cube#[]} method.
class Dimension < Base
include Enumerable
# The {Cube} to which this dimension belongs
attr_reader :cube
# @return [String] the name of the dimension.
attr_reader :name
# @return [String] the storage type: Dense or Sparse.
attr_reader :storage_type
# @return the dimension tag: Accounts, Time, Attribute, etc.
attr_reader :tag
# @!visibility private
#
# Creates a new Dimension object, populated from the supplied IEssDimension
# object.
#
# @param cube [Cube] The cube to which this dimension belongs,
# @param ess_dim [IEssDimension] The JAPI IEssDimension object this class
# is to wrap.
def initialize(cube, ess_dim)
super(cube.log)
@name = ess_dim.name
@storage_type = ess_dim.storage_type.to_s
@tag = ess_dim.tag.to_s
@cube = cube
@root_member = nil
end
# @return [Boolean] true if this dimension is dense, false if it is not.
def dense?
@storage_type == 'Dense'
end
# @return [Boolean] true if this dimension is sparse or an attribute
# dimension.
def sparse?
@storage_type == 'Sparse' && !(@tag =~ /^Attr/)
end
# @return [Boolean] true if this dimension is an attribute dimension,
# false otherwise.
def attribute_dimension?
@storage_type == 'Sparse' && (@tag =~ /^Attr/)
end
# @return [Boolean] true unless this dimension is an attribute dimension.
def non_attribute_dimension?
!attribute_dimension?
end
# @return [Member] The top-most member in the dimension (i.e. the member
# with the same name as the dimension).
def root_member
retrieve_members unless @members
@root_member
end
# Returns a {Member} object containing details about the dimension member
# +mbr_name+.
#
# @param mbr_name [String] A name or alias for the member to be returned.
# An Essbase substitution variable can also be passed, in which case
# the variable value is retrieved, and the corresponding {Member} object
# returned.
#
# @return [Member] if the named member was found in this dimension.
# @return [NilClass] if no matching member can be found.
def [](mbr_name)
retrieve_members unless @members
case mbr_name
when /^['"\[]?&(.+?)['"\]]?$/
# Substitution variable
mbr_name = @cube.get_substitution_variable_value($1)
when /^['"\[]?(.+?)['"\]]?$/
# Quoted
mbr_name = $1
end
mbr = @member_lookup[mbr_name.upcase]
unless mbr
# Search by alias
@cube.get_alias_table_names.each do |tbl|
mbr = @members.find{ |mbr| (al = mbr.alias(tbl)) &&
(al.upcase == mbr_name.upcase) }
break if mbr
end
end
mbr
end
# Takes a +mbr_spec+ and expands it into an Array of matching Member
# objects.
#
# Member names may be followed by various macros indicating relations of
# the member to return, or alternatively, an Essbase calc function may be
# used to query the outline for matching members.
#
# Relationship macros cause a member to be replaced by an expansion set
# of members that have that relationship to the member. A macro is specified
# by the addition of a +.<Relation>+ suffix, e.g. <Member>.Children.
# Additionally, the relationship in question may be further qualified by +I+
# and/or +R+ modifiers, where +I+ means include the member itself in the
# expansion set, and +R+ means consider all hierarchies when expanding the
# member.
#
# The following relationship macros are supported:
# - +.Parent+ returns the member parent
# - +.[I,R]Ancestors+ returns the member's ancestors
# - +.[I]Children+ returns the member's children; supports the I modifier
# - +.[I,R]Descendants+ returns the member's descendants
# - +.[R]Leaves+ or +.[R]Level0+ returns the leaf/level 0 descendants of
# the member
# - +.[R]Level<N>+ returns the related members at level _N_
# - +.[R]Generation<N>+ returns the related members at generation _N_
# - +.UDA(<uda>)+ returns descendants of the member that have the UDA <uda>
#
# All of the above do not require querying of Essbase, and so are cheap
# to evaluate. Alternatively, Essbase calc functions can be used to express
# more complicated relationships, such as compound relationships.
#
# The +mbr_spec+ can be a single specification (using the macros or calc
# syntax described), or it can an array of specifications, each of which
# is expanded to the corresponding set of member(s). By default, each such
# set of member(s) is appended to the result, but several other possibilities
# are supported, using an optional operation type prefix:
# - :add <spec> or + <spec>: The member set is appended to the results;
# this is the default behaviour when no operation type is specified.
# - :minus <spec> or - <spec>: The resulting member(s) are removed from
# the results. Members in this set that are not in the results are
# ignored.
# - :filter <ruby expr>: The current result set is filtered to only
# include members that satisy <ruby expr>. The results are always
# Member object instances, so the filter expression can use any
# properties of the members to define the filter condition.
# - :map <ruby expor>: The current result set is mapped using <ruby expr>,
# e.g. ":map parent" would convert the results to the parents of the
# members currently in the result set. The result of the :map operation
# should be Member objects.
# - :unique: Removes duplicates from the result set.
#
# @param mbr_spec [Array|String] A string or array of strings containing
# member names, optionally followed by an expansion macro, such as
# .Children, .Leaves, .Descendants, etc
# @return [Array<Member>] An array of Member objects representing the
def expand_members(mbr_spec, options={})
retrieve_members unless @members
mbr_spec = [mbr_spec].flatten
all_mbrs = []
mbr_spec.each do |spec|
spec.strip!
case spec
when /^(?:\-|[:!](?:minus|not)\s)\s*(.+)/
all_mbrs -= process_member_spec($1)
when /^(?:\+|[:!](?:add|or)\s)\s*(.+)/
all_mbrs += process_member_spec($1)
when /^[:!]and\s+(.+)/ # Can't use & as a shortcut, since that identifies a subvar
all_mbrs = all_mbrs & process_member_spec($1)
when /^[:!]filter\s+(.+)/
spec = eval("lambda{ #{$1} }")
all_mbrs.select!{ |mbr| mbr.instance_exec(&spec) }
when /^[:!]map\s+(.+)/
spec = eval("lambda{ #{$1} }")
all_mbrs.map!{ |mbr| mbr.instance_exec(&spec) }.flatten!
when /^[!:]uniq(ue)?\s*$/
all_mbrs.uniq!
else
all_mbrs.concat(process_member_spec(spec))
end
end
if all_mbrs.size == 0 && options.fetch(:raise_if_empty, true)
raise ArgumentError, "Member specification #{mbr_spec} for #{self.name} returned no members"
end
all_mbrs
end
# Takes a +spec+ and expands it into an Array of matching Member objects.
#
# Member names may be followed by various macros indicating relations of
# the member to return, or alternatively, an Essbase calc function may be
# used to query the outline for matching members.
#
# Relationship macros cause a member to be replaced by an expansion set
# of members that have that relationship to the member. A macro is specified
# by the addition of a +.<Relation>+ suffix, e.g. <Member>.Children.
# Additionally, the relationship in question may be further qualified by +I+
# and/or +R+ modifiers, where +I+ means include the member itself in the
# expansion set, and +R+ means consider all hierarchies when expanding the
# member.
#
# The following relationship macros are supported:
# - +.Parent+ returns the member parent
# - +.[I,R]Ancestors+ returns the member's ancestors
# - +.[I]Children+ returns the member's children; supports the I modifier
# - +.[I,R]Descendants+ returns the member's descendants
# - +.[R]Leaves+ or +.[R]Level0+ returns the leaf/level 0 descendants of
# the member
# - +.[R]Level<N>+ returns the related members at level _N_
# - +.[R]Generation<N>+ returns the related members at generation _N_
# - + .[I]Shared returns all other instances of the member
# - +.UDA(<uda>)+ returns descendants of the member that have the UDA <uda>
#
# All of the above do not require querying of Essbase, and so are cheap
# to evaluate. Alternatively, Essbase calc functions can be used to express
# more complicated relationships, such as compound relationships.
def process_member_spec(spec)
case spec.strip
when /^['"\[]?(.+?)['"\]]?\.(Parent|I?Children|I?R?Descendants|I?R?Ancestors|R?Level0|R?Leaves|I?Shared)$/i
# Memer name with expansion macro
mbr = self[$1]
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}' in #{spec}" unless mbr
mthd = $2.downcase
mthd += '_members' if mthd =~ /shared$/
rels = mbr.send(mthd.intern)
rels.is_a?(Array) ? rels : [rels]
when /^['"\[]?(.+?)['"\]]?\.(R)?(Level|Generation|Relative)\(?(\d+)\)?$/i
# Memer name with level/generation expansion macro
mbr = self[$1]
sign = $3.downcase == 'level' ? -1 : 1
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}' in #{spec}" unless mbr
mbr.relative($4.to_i * sign, !!$2)
when /^['"\[]?(.+?)['"\]]?\.UDA\(['"]?(.+?)['"]?\)$/i
# Memer name with UDA expansion macro
mbr = self[$1]
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}' in #{spec}" unless mbr
mbr.idescendants.select{ |mbr| mbr.has_uda?($2) }
when /[@:,]/
# An Essbase calc function or range - execute query and use results to find Member objects
mbrs = []
mbr_sel = try{ @cube.open_member_selection("MemberQuery") }
begin
mbr_sel.execute_query(<<-EOQ.strip, spec)
<OutputType Binary
<SelectMbrInfo(MemberName, ParentMemberName)
EOQ
mbr_sel.get_members && mbr_sel.get_members.get_all.each do |ess_mbr|
mbr = self[ess_mbr.name]
raise ArgumentError, "No member in #{self.name} named '#{ess_mbr.name}'" unless mbr
if mbr.parent && mbr.parent.name != ess_mbr.parent_member_name
mbr = mbr.shared_members.find{ |mbr| mbr.parent.name == ess_mbr.parent_member_name }
raise "Cannot locate #{ess_mbr.name} with parent #{ess_mbr.parent_member_name}" unless mbr
end
mbrs << mbr
end
ensure
mbr_sel.close
end
mbrs
when /^['"\[]?(.+?)['"\]]?$/
# Plain member name
mbr = self[$1]
raise ArgumentError, "Unrecognised #{self.name} member '#{$1}'" unless mbr
[mbr]
else
raise ArgumentError, "Unrecognised #{self.name} member '#{spec}'"
end
end
# Performs a traversal of the dimension hierarchy, yielding each Member
# in the dimension to the supplied block.
#
# @note By default, this iteration of members excludes shared members,
# but if these are desired, specify true in the :include_shared option.
#
# @param opts [Hash] An options hash.
# @option opts [Boolean] :include_shared If true, includes shared members
# when iterating over the dimension. If false (the default), shared
# members are not yielded.
#
# @yield Yields a {Member} object for each member in the dimension.
# @yieldparam mbr [Member] The current member in the iteration.
def each(opts = {})
retrieve_members unless @members
include_shared = opts.fetch(:include_shared, false)
@members.each do |mbr|
yield mbr unless mbr.shared? || include_shared
end
end
# Performs a depth-first traversal of the dimension, yielding members
# to the supplied block. A depth-first traversal yields members in
# outline order.
#
# @yield Yields each member of the dimension as it is visited
# @yieldparam mbr [Member] A member of the dimension
def walk(options = {}, &blk)
retrieve_members unless @members
@root_member.traverse(0, options, &blk)
end
# Retrieves the current set of members for this dimension.
#
# Note: this method is called automatically the first time a member is
# requested from a dimension, and so would not normally need to be called
# directly unless you wish to refresh the dimension members, e.g. after
# a dimension build.
def retrieve_members
@root_member = nil
@members = []
shared = []
@member_lookup = {}
log.finer "Retrieving members of dimension '#{@name}'"
alias_tbls = try{ @cube.get_alias_table_names.to_a }
mbr_sel = try{ @cube.open_member_selection("MemberQuery") }
begin
spec = %Q{@IDESCENDANTS("#{self.name}")}
query = <<-EOQ.strip
<OutputType Binary
<SelectMbrInfo(MemberName, MemberAliasName, ParentMemberName,
MemberGeneration, MemberLevel, Consolidation,
ShareOption, MemberFormula, UDAList)
EOQ
@cube.instrument 'retrieve_members', dimension: self do
try{ mbr_sel.execute_query(query, spec) }
end
mbr_sel.get_members.get_all.each do |ess_mbr|
mbr = Member.new(self, ess_mbr, alias_tbls)
@members << mbr
if mbr.shared?
shared << mbr
else
@member_lookup[mbr.name.upcase] = mbr
end
end
# Link shared members to non-shared member (and vice versa)
shared.each do |smbr|
mbr = @member_lookup[smbr.name.upcase]
smbr.instance_variable_set(:@non_shared_member, mbr)
mbr.instance_variable_get(:@shared_members) << smbr
end
@root_member = @member_lookup[self.name.upcase]
# Convert parent names to references to the parent Member object
# This can only be done after we've seen all members, since the
# member selection query returns parents after children
@members.each do |mbr|
par = @member_lookup[mbr.parent.upcase]
mbr.instance_variable_set(:@parent, par)
par.instance_variable_get(:@children) << mbr if par
end
ensure
try{ mbr_sel.close }
end
log.finer "Retrieved #{@members.size} members"
end
# Returns the name of the dimension
def to_s
@name
end
end
end
|
Pod::Spec.new do |s|
s.name = "EMCCountryPickerController"
s.version = "1.3.2"
s.summary = "EMCCountryPickerController is a view controller allowing users to choose and filter countries in a list."
s.description = <<-DESC
`EMCCountryPickerController` is a view controller that allow users to choose
a country from a searchable list. The available countries are taken from the
[ISO 3166-1 standard][iso3166], whose [ISO 3166-1 alpha-2] two-letter country
codes are used internally by the controller implementation. Public domain
flags are available for every country.
DESC
s.homepage = "https://github.com/emcrisostomo/EMCCountryPickerController"
s.license = { :type => "BSD", :file => "LICENSE" }
s.author = { "Enrico M. Crisostomo" => "http://thegreyblog.blogspot.com/" }
s.social_media_url = "http://thegreyblog.blogspot.com"
s.platform = :ios, "6.1"
s.source = { :git => "https://github.com/emcrisostomo/EMCCountryPickerController.git", :tag => "1.3.2" }
s.source_files = "EMCCountryPickerController", "EMCCountryPickerController/**/*.{h,m}"
s.exclude_files = "EMCCountryPickerController/Exclude"
s.resources = "EMCCountryPickerController/EMCCountryPickerController.bundle"
s.requires_arc = true
end
Bump v. 1.3.3
Pod::Spec.new do |s|
s.name = "EMCCountryPickerController"
s.version = "1.3.3"
s.summary = "EMCCountryPickerController is a view controller allowing users to choose and filter countries in a list."
s.description = <<-DESC
`EMCCountryPickerController` is a view controller that allow users to choose
a country from a searchable list. The available countries are taken from the
[ISO 3166-1 standard][iso3166], whose [ISO 3166-1 alpha-2] two-letter country
codes are used internally by the controller implementation. Public domain
flags are available for every country.
DESC
s.homepage = "https://github.com/emcrisostomo/EMCCountryPickerController"
s.license = { :type => "BSD", :file => "LICENSE" }
s.author = { "Enrico M. Crisostomo" => "http://thegreyblog.blogspot.com/" }
s.social_media_url = "http://thegreyblog.blogspot.com"
s.platform = :ios, "6.1"
s.source = { :git => "https://github.com/emcrisostomo/EMCCountryPickerController.git", :tag => "1.3.3" }
s.source_files = "EMCCountryPickerController", "EMCCountryPickerController/**/*.{h,m}"
s.exclude_files = "EMCCountryPickerController/Exclude"
s.resources = "EMCCountryPickerController/EMCCountryPickerController.bundle"
s.requires_arc = true
end
|
# coding: utf-8
require 'helper'
# Intercept STDOUT and collect it
class Boom::Command
def self.capture_output
@output = ''
end
def self.captured_output
@output
end
def self.output(s)
@output << s
end
def self.save!
# no-op
end
end
class TestCommand < Test::Unit::TestCase
def setup
boom_json :urls
end
def command(cmd)
cmd = cmd.split(' ') if cmd
Boom::Command.capture_output
Boom::Command.execute(*cmd)
output = Boom::Command.captured_output
output.gsub(/\e\[\d\d?m/, '')
end
def test_overview_for_empty
storage = Boom::Storage
storage.stubs(:lists).returns([])
Boom::Command.stubs(:storage).returns(storage)
assert_match /have anything yet!/, command(nil)
end
def test_overview
assert_equal ' urls (2)', command(nil)
end
def test_list_detail
assert_match /github/, command('urls')
end
def test_list_all
cmd = command('all')
assert_match /urls/, cmd
assert_match /github/, cmd
end
def test_list_creation
assert_match /a new list called newlist/, command('newlist')
end
def test_list_creation_with_item
assert_match /a new list called newlist.* item in newlist/, command('newlist item blah')
end
def test_list_creation_with_item_stdin
STDIN.stubs(:read).returns('blah')
STDIN.stubs(:stat)
STDIN.stat.stubs(:size).returns(4)
assert_match /a new list called newlist.* item in newlist is blah/, command('newlist item')
end
def test_list_creation_with_existing_items_name
command('list item foo')
assert_match /a new list called item.* key in item is foo/, command('item key bar')
end
def test_item_access
IO.stubs(:popen)
assert_match /copied https:\/\/github\.com to your clipboard/,
command('github')
end
def test_item_access_scoped_by_list
IO.stubs(:popen)
assert_match /copied https:\/\/github\.com to your clipboard/,
command('urls github')
end
def test_item_open_item
Boom::Platform.stubs(:system).returns('')
assert_match /opened https:\/\/github\.com for you/, command('open github')
end
def test_item_open_specific_item
Boom::Platform.stubs(:system).returns('')
assert_match /opened https:\/\/github\.com for you/, command('open urls github')
end
def test_item_open_lists
Boom::Platform.stubs(:system).returns('')
assert_match /opened all of urls for you/, command('open urls')
end
def test_item_creation
assert_match /twitter in urls/,
command('urls twitter http://twitter.com/holman')
end
def test_item_creation_long_value
assert_match /is tanqueray hendricks bombay/,
command('urls gins tanqueray hendricks bombay')
end
def test_list_deletion_no
STDIN.stubs(:gets).returns('n')
assert_match /Just kidding then/, command('urls delete')
end
def test_list_deletion_yes
STDIN.stubs(:gets).returns('y')
assert_match /Deleted all your urls/, command('urls delete')
end
def test_item_deletion
assert_match /github is gone forever/, command('urls github delete')
end
def test_edit
Boom::Platform.stubs(:system).returns('')
assert_match 'Make your edits', command('edit')
end
def test_help
assert_match 'boom help', command('help')
assert_match 'boom help', command('-h')
assert_match 'boom help', command('--help')
end
def test_noop_options
assert_match 'boom help', command('--anything')
assert_match 'boom help', command('-d')
end
def test_nonexistent_item_access_scoped_by_list
assert_match /twitter not found in urls/, command('urls twitter')
end
def test_echo_item
assert_match /https:\/\/github\.com/, command('echo github')
end
def test_echo_item_shorthand
assert_match /https:\/\/github\.com/, command('e github')
end
def test_echo_item_does_not_exist
assert_match /wrong not found/, command('echo wrong')
end
def test_echo_list_item
assert_match /https:\/\/github\.com/, command('echo urls github')
end
def test_echo_list_item_does_not_exist
assert_match /wrong not found in urls/, command('echo urls wrong')
end
def test_show_storage
Boom::Config.any_instance.stubs(:attributes).returns('backend' => 'json')
assert_match /You're currently using json/, command('storage')
end
def test_nonexistant_storage_switch
Boom::Config.any_instance.stubs(:save).returns(true)
assert_match /couldn't find that storage engine/, command('switch dkdkdk')
end
def test_storage_switch
Boom::Config.any_instance.stubs(:save).returns(true)
assert_match /We've switched you over to redis/, command('switch redis')
end
def test_version_switch
assert_match /#{Boom::VERSION}/, command('-v')
end
def test_version_long
assert_match /#{Boom::VERSION}/, command('--version')
end
def test_stdin_pipes
stub = Object.new
stub.stubs(:stat).returns([1,2])
stub.stubs(:read).returns("http://twitter.com")
Boom::Command.stubs(:stdin).returns(stub)
assert_match /twitter in urls/, command('urls twitter')
end
def test_random
Boom::Platform.stubs(:system).returns('')
assert_match /opened .+ for you/, command('random')
end
def test_random_from_list
Boom::Platform.stubs(:system).returns('')
assert_match /(github|zachholman)/, command('random urls')
end
def test_random_list_not_exist
Boom::Platform.stubs(:system).returns('')
assert_match /couldn't find that list\./, command('random 39jc02jlskjbbac9')
end
def test_delete_item_list_not_exist
assert_match /couldn't find that list\./, command('urlz github delete')
end
def test_delete_item_wrong_list
command('urlz twitter https://twitter.com/')
assert_match /github not found in urlz/, command('urlz github delete')
end
def test_delete_item_different_name
command('foo bar baz')
assert_match /bar is gone forever/, command('foo bar delete')
end
def test_delete_item_same_name
command('duck duck goose')
assert_match /duck is gone forever/, command('duck duck delete')
end
end
Fix broken test for creating a list with an existing item's name
# coding: utf-8
require 'helper'
# Intercept STDOUT and collect it
class Boom::Command
def self.capture_output
@output = ''
end
def self.captured_output
@output
end
def self.output(s)
@output << s
end
def self.save!
# no-op
end
end
class TestCommand < Test::Unit::TestCase
def setup
boom_json :urls
end
def command(cmd)
cmd = cmd.split(' ') if cmd
Boom::Command.capture_output
Boom::Command.execute(*cmd)
output = Boom::Command.captured_output
output.gsub(/\e\[\d\d?m/, '')
end
def test_overview_for_empty
storage = Boom::Storage
storage.stubs(:lists).returns([])
Boom::Command.stubs(:storage).returns(storage)
assert_match /have anything yet!/, command(nil)
end
def test_overview
assert_equal ' urls (2)', command(nil)
end
def test_list_detail
assert_match /github/, command('urls')
end
def test_list_all
cmd = command('all')
assert_match /urls/, cmd
assert_match /github/, cmd
end
def test_list_creation
assert_match /a new list called newlist/, command('newlist')
end
def test_list_creation_with_item
assert_match /a new list called newlist.* item in newlist/, command('newlist item blah')
end
def test_list_creation_with_item_stdin
STDIN.stubs(:read).returns('blah')
STDIN.stubs(:stat)
STDIN.stat.stubs(:size).returns(4)
assert_match /a new list called newlist.* item in newlist is blah/, command('newlist item')
end
def test_list_creation_with_existing_items_name
command('list item foo')
assert_match /a new list called item.* key in item is bar/, command('item key bar')
end
def test_item_access
IO.stubs(:popen)
assert_match /copied https:\/\/github\.com to your clipboard/,
command('github')
end
def test_item_access_scoped_by_list
IO.stubs(:popen)
assert_match /copied https:\/\/github\.com to your clipboard/,
command('urls github')
end
def test_item_open_item
Boom::Platform.stubs(:system).returns('')
assert_match /opened https:\/\/github\.com for you/, command('open github')
end
def test_item_open_specific_item
Boom::Platform.stubs(:system).returns('')
assert_match /opened https:\/\/github\.com for you/, command('open urls github')
end
def test_item_open_lists
Boom::Platform.stubs(:system).returns('')
assert_match /opened all of urls for you/, command('open urls')
end
def test_item_creation
assert_match /twitter in urls/,
command('urls twitter http://twitter.com/holman')
end
def test_item_creation_long_value
assert_match /is tanqueray hendricks bombay/,
command('urls gins tanqueray hendricks bombay')
end
def test_list_deletion_no
STDIN.stubs(:gets).returns('n')
assert_match /Just kidding then/, command('urls delete')
end
def test_list_deletion_yes
STDIN.stubs(:gets).returns('y')
assert_match /Deleted all your urls/, command('urls delete')
end
def test_item_deletion
assert_match /github is gone forever/, command('urls github delete')
end
def test_edit
Boom::Platform.stubs(:system).returns('')
assert_match 'Make your edits', command('edit')
end
def test_help
assert_match 'boom help', command('help')
assert_match 'boom help', command('-h')
assert_match 'boom help', command('--help')
end
def test_noop_options
assert_match 'boom help', command('--anything')
assert_match 'boom help', command('-d')
end
def test_nonexistent_item_access_scoped_by_list
assert_match /twitter not found in urls/, command('urls twitter')
end
def test_echo_item
assert_match /https:\/\/github\.com/, command('echo github')
end
def test_echo_item_shorthand
assert_match /https:\/\/github\.com/, command('e github')
end
def test_echo_item_does_not_exist
assert_match /wrong not found/, command('echo wrong')
end
def test_echo_list_item
assert_match /https:\/\/github\.com/, command('echo urls github')
end
def test_echo_list_item_does_not_exist
assert_match /wrong not found in urls/, command('echo urls wrong')
end
def test_show_storage
Boom::Config.any_instance.stubs(:attributes).returns('backend' => 'json')
assert_match /You're currently using json/, command('storage')
end
def test_nonexistant_storage_switch
Boom::Config.any_instance.stubs(:save).returns(true)
assert_match /couldn't find that storage engine/, command('switch dkdkdk')
end
def test_storage_switch
Boom::Config.any_instance.stubs(:save).returns(true)
assert_match /We've switched you over to redis/, command('switch redis')
end
def test_version_switch
assert_match /#{Boom::VERSION}/, command('-v')
end
def test_version_long
assert_match /#{Boom::VERSION}/, command('--version')
end
def test_stdin_pipes
stub = Object.new
stub.stubs(:stat).returns([1,2])
stub.stubs(:read).returns("http://twitter.com")
Boom::Command.stubs(:stdin).returns(stub)
assert_match /twitter in urls/, command('urls twitter')
end
def test_random
Boom::Platform.stubs(:system).returns('')
assert_match /opened .+ for you/, command('random')
end
def test_random_from_list
Boom::Platform.stubs(:system).returns('')
assert_match /(github|zachholman)/, command('random urls')
end
def test_random_list_not_exist
Boom::Platform.stubs(:system).returns('')
assert_match /couldn't find that list\./, command('random 39jc02jlskjbbac9')
end
def test_delete_item_list_not_exist
assert_match /couldn't find that list\./, command('urlz github delete')
end
def test_delete_item_wrong_list
command('urlz twitter https://twitter.com/')
assert_match /github not found in urlz/, command('urlz github delete')
end
def test_delete_item_different_name
command('foo bar baz')
assert_match /bar is gone forever/, command('foo bar delete')
end
def test_delete_item_same_name
command('duck duck goose')
assert_match /duck is gone forever/, command('duck duck delete')
end
end
|
# encoding: utf-8
class Cri::CommandTestCase < Cri::TestCase
def simple_cmd
Cri::Command.define do
name 'moo'
usage 'moo [options] arg1 arg2 ...'
summary 'does stuff'
description 'This command does a lot of stuff.'
option :a, :aaa, 'opt a', :argument => :optional do |value, cmd|
$stdout.puts "#{cmd.name}:#{value}"
end
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
run do |opts, args, c|
$stdout.puts "Awesome #{c.name}!"
$stdout.puts args.join(',')
opts_strings = []
opts.each_pair { |k,v| opts_strings << "#{k}=#{v}" }
$stdout.puts opts_strings.sort.join(',')
end
end
end
def bare_cmd
Cri::Command.define do
name 'moo'
run do |opts, args|
end
end
end
def nested_cmd
super_cmd = Cri::Command.define do
name 'super'
usage 'super [command] [options] [arguments]'
summary 'does super stuff'
description 'This command does super stuff.'
option :a, :aaa, 'opt a', :argument => :optional do |value, cmd|
$stdout.puts "#{cmd.name}:#{value}"
end
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
end
super_cmd.define_command do
name 'sub'
aliases 'sup'
usage 'sub [options]'
summary 'does subby stuff'
description 'This command does subby stuff.'
option :m, :mmm, 'opt m', :argument => :optional
required :n, :nnn, 'opt n'
optional :o, :ooo, 'opt o'
flag :p, :ppp, 'opt p'
forbidden :q, :qqq, 'opt q'
run do |opts, args|
$stdout.puts "Sub-awesome!"
$stdout.puts args.join(',')
opts_strings = []
opts.each_pair { |k,v| opts_strings << "#{k}=#{v}" }
$stdout.puts opts_strings.join(',')
end
end
super_cmd.define_command do
name 'sink'
usage 'sink thing_to_sink'
summary 'sinks stuff'
description 'Sinks stuff (like ships and the like).'
run do |opts, args|
$stdout.puts "Sinking!"
end
end
super_cmd
end
def nested_cmd_with_run_block
super_cmd = Cri::Command.define do
name 'super'
usage 'super [command] [options] [arguments]'
summary 'does super stuff'
description 'This command does super stuff.'
run do |opts, args|
$stdout.puts "super"
end
end
super_cmd.define_command do
name 'sub'
aliases 'sup'
usage 'sub [options]'
summary 'does subby stuff'
description 'This command does subby stuff.'
run do |opts, args|
$stdout.puts "sub"
end
end
super_cmd
end
def test_invoke_simple_without_opts_or_args
out, err = capture_io_while do
simple_cmd.run(%w())
end
assert_equal [ 'Awesome moo!', '', '' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_args
out, err = capture_io_while do
simple_cmd.run(%w(abc xyz))
end
assert_equal [ 'Awesome moo!', 'abc,xyz', '' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_opts
out, err = capture_io_while do
simple_cmd.run(%w(-c -b x))
end
assert_equal [ 'Awesome moo!', '', 'bbb=x,ccc=true' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_missing_opt_arg
out, err = capture_io_while do
assert_raises SystemExit do
simple_cmd.run(%w( -b ))
end
end
assert_equal [], lines(out)
assert_equal [ "moo: option requires an argument -- b" ], lines(err)
end
def test_invoke_simple_with_illegal_opt
out, err = capture_io_while do
assert_raises SystemExit do
simple_cmd.run(%w( -z ))
end
end
assert_equal [], lines(out)
assert_equal [ "moo: illegal option -- z" ], lines(err)
end
def test_invoke_simple_with_opt_with_block
out, err = capture_io_while do
simple_cmd.run(%w( -a 123 ))
end
assert_equal [ 'moo:123', 'Awesome moo!', '', 'aaa=123' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_nested_without_opts_or_args
out, err = capture_io_while do
assert_raises SystemExit do
nested_cmd.run(%w())
end
end
assert_equal [ ], lines(out)
assert_equal [ 'super: no command given' ], lines(err)
end
def test_invoke_nested_with_correct_command_name
out, err = capture_io_while do
nested_cmd.run(%w( sub ))
end
assert_equal [ 'Sub-awesome!', '', '' ], lines(out)
assert_equal [ ], lines(err)
end
def test_invoke_nested_with_incorrect_command_name
out, err = capture_io_while do
assert_raises SystemExit do
nested_cmd.run(%w( oogabooga ))
end
end
assert_equal [ ], lines(out)
assert_equal [ "super: unknown command 'oogabooga'" ], lines(err)
end
def test_invoke_nested_with_ambiguous_command_name
out, err = capture_io_while do
assert_raises SystemExit do
nested_cmd.run(%w( s ))
end
end
assert_equal [ ], lines(out)
assert_equal [ "super: 's' is ambiguous:", " sink sub" ], lines(err)
end
def test_invoke_nested_with_alias
out, err = capture_io_while do
nested_cmd.run(%w( sup ))
end
assert_equal [ 'Sub-awesome!', '', '' ], lines(out)
assert_equal [ ], lines(err)
end
def test_invoke_nested_with_options_before_command
out, err = capture_io_while do
nested_cmd.run(%w( -a 666 sub ))
end
assert_equal [ 'super:666', 'Sub-awesome!', '', 'aaa=666' ], lines(out)
assert_equal [ ], lines(err)
end
def test_invoke_nested_with_run_block
out, err = capture_io_while do
nested_cmd_with_run_block.run(%w())
end
assert_equal [ 'super' ], lines(out)
assert_equal [ ], lines(err)
out, err = capture_io_while do
nested_cmd_with_run_block.run(%w( sub ))
end
assert_equal [ 'sub' ], lines(out)
assert_equal [ ], lines(err)
end
def test_help_nested
help = nested_cmd.subcommands.find { |cmd| cmd.name == 'sub' }.help
assert help.include?("USAGE\e[0m\e[0m\n \e[32msuper\e[0m \e[32msub\e[0m [options]\n")
end
def test_help_for_bare_cmd
bare_cmd.help
end
def test_help_with_optional_options
cmd = Cri::Command.define do
name 'build'
flag :s, nil, 'short'
flag nil, :long, 'long'
end
help = cmd.help
assert_match(/--long.*-s/m, help)
assert_match(/^\e\[33m --long \e\[0mlong$/, help)
assert_match(/^\e\[33m -s \e\[0mshort$/, help)
end
def test_help_with_multiple_groups
help = nested_cmd.subcommands.find { |cmd| cmd.name == 'sub' }.help
assert_match(/OPTIONS.*OPTIONS FOR SUPER/m, help)
end
def test_modify_with_block_argument
cmd = Cri::Command.define do |c|
c.name 'build'
end
assert_equal 'build', cmd.name
cmd.modify do |c|
c.name 'compile'
end
assert_equal 'compile', cmd.name
end
def test_modify_without_block_argument
cmd = Cri::Command.define do
name 'build'
end
assert_equal 'build', cmd.name
cmd.modify do
name 'compile'
end
assert_equal 'compile', cmd.name
end
def test_new_basic_root
cmd = Cri::Command.new_basic_root.modify do
name 'mytool'
end
# Check option definitions
assert_equal 1, cmd.option_definitions.size
opt_def = cmd.option_definitions.to_a[0]
assert_equal 'help', opt_def[:long]
# Check subcommand
assert_equal 1, cmd.subcommands.size
assert_equal 'help', cmd.subcommands.to_a[0].name
end
def test_define_with_block_argument
cmd = Cri::Command.define do |c|
c.name 'moo'
end
assert_equal 'moo', cmd.name
end
def test_define_without_block_argument
cmd = Cri::Command.define do
name 'moo'
end
assert_equal 'moo', cmd.name
end
def test_define_subcommand_with_block_argument
cmd = bare_cmd
cmd.define_command do |c|
c.name 'baresub'
end
assert_equal 'baresub', cmd.subcommands.to_a[0].name
end
def test_define_subcommand_without_block_argument
cmd = bare_cmd
cmd.define_command do
name 'baresub'
end
assert_equal 'baresub', cmd.subcommands.to_a[0].name
end
def test_backtrace_includes_filename
error = assert_raises RuntimeError do
Cri::Command.define('raise "boom"', 'mycommand.rb')
end
assert_match /mycommand.rb/, error.backtrace.join("\n")
end
def test_hidden_commands_single
cmd = nested_cmd
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'old-and-deprecated'
c.summary 'does stuff the ancient, totally deprecated way'
c.be_hidden
end
refute cmd.help.include?('hidden commands omitted')
assert cmd.help.include?('hidden command omitted')
refute cmd.help.include?('old-and-deprecated')
refute cmd.help(:verbose => true).include?('hidden commands omitted')
refute cmd.help(:verbose => true).include?('hidden command omitted')
assert cmd.help(:verbose => true).include?('old-and-deprecated')
end
def test_hidden_commands_multiple
cmd = nested_cmd
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'first'
c.summary 'does stuff first'
end
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'old-and-deprecated'
c.summary 'does stuff the old, deprecated way'
c.be_hidden
end
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'ancient-and-deprecated'
c.summary 'does stuff the ancient, reallydeprecated way'
c.be_hidden
end
assert cmd.help.include?('hidden commands omitted')
refute cmd.help.include?('hidden command omitted')
refute cmd.help.include?('old-and-deprecated')
refute cmd.help.include?('ancient-and-deprecated')
refute cmd.help(:verbose => true).include?('hidden commands omitted')
refute cmd.help(:verbose => true).include?('hidden command omitted')
assert cmd.help(:verbose => true).include?('old-and-deprecated')
assert cmd.help(:verbose => true).include?('ancient-and-deprecated')
pattern = /ancient-and-deprecated.*first.*old-and-deprecated/m
assert_match(pattern, cmd.help(:verbose => true))
end
def test_run_with_raw_args
cmd = Cri::Command.define do
name 'moo'
run do |opts, args|
puts "args=#{args.join(',')} args.raw=#{args.raw.join(',')}"
end
end
out, err = capture_io_while do
cmd.run(%w( foo -- bar ))
end
assert_equal "args=foo,bar args.raw=foo,--,bar\n", out
end
end
Add raw args test for command runners
# encoding: utf-8
class Cri::CommandTestCase < Cri::TestCase
def simple_cmd
Cri::Command.define do
name 'moo'
usage 'moo [options] arg1 arg2 ...'
summary 'does stuff'
description 'This command does a lot of stuff.'
option :a, :aaa, 'opt a', :argument => :optional do |value, cmd|
$stdout.puts "#{cmd.name}:#{value}"
end
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
run do |opts, args, c|
$stdout.puts "Awesome #{c.name}!"
$stdout.puts args.join(',')
opts_strings = []
opts.each_pair { |k,v| opts_strings << "#{k}=#{v}" }
$stdout.puts opts_strings.sort.join(',')
end
end
end
def bare_cmd
Cri::Command.define do
name 'moo'
run do |opts, args|
end
end
end
def nested_cmd
super_cmd = Cri::Command.define do
name 'super'
usage 'super [command] [options] [arguments]'
summary 'does super stuff'
description 'This command does super stuff.'
option :a, :aaa, 'opt a', :argument => :optional do |value, cmd|
$stdout.puts "#{cmd.name}:#{value}"
end
required :b, :bbb, 'opt b'
optional :c, :ccc, 'opt c'
flag :d, :ddd, 'opt d'
forbidden :e, :eee, 'opt e'
end
super_cmd.define_command do
name 'sub'
aliases 'sup'
usage 'sub [options]'
summary 'does subby stuff'
description 'This command does subby stuff.'
option :m, :mmm, 'opt m', :argument => :optional
required :n, :nnn, 'opt n'
optional :o, :ooo, 'opt o'
flag :p, :ppp, 'opt p'
forbidden :q, :qqq, 'opt q'
run do |opts, args|
$stdout.puts "Sub-awesome!"
$stdout.puts args.join(',')
opts_strings = []
opts.each_pair { |k,v| opts_strings << "#{k}=#{v}" }
$stdout.puts opts_strings.join(',')
end
end
super_cmd.define_command do
name 'sink'
usage 'sink thing_to_sink'
summary 'sinks stuff'
description 'Sinks stuff (like ships and the like).'
run do |opts, args|
$stdout.puts "Sinking!"
end
end
super_cmd
end
def nested_cmd_with_run_block
super_cmd = Cri::Command.define do
name 'super'
usage 'super [command] [options] [arguments]'
summary 'does super stuff'
description 'This command does super stuff.'
run do |opts, args|
$stdout.puts "super"
end
end
super_cmd.define_command do
name 'sub'
aliases 'sup'
usage 'sub [options]'
summary 'does subby stuff'
description 'This command does subby stuff.'
run do |opts, args|
$stdout.puts "sub"
end
end
super_cmd
end
def test_invoke_simple_without_opts_or_args
out, err = capture_io_while do
simple_cmd.run(%w())
end
assert_equal [ 'Awesome moo!', '', '' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_args
out, err = capture_io_while do
simple_cmd.run(%w(abc xyz))
end
assert_equal [ 'Awesome moo!', 'abc,xyz', '' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_opts
out, err = capture_io_while do
simple_cmd.run(%w(-c -b x))
end
assert_equal [ 'Awesome moo!', '', 'bbb=x,ccc=true' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_simple_with_missing_opt_arg
out, err = capture_io_while do
assert_raises SystemExit do
simple_cmd.run(%w( -b ))
end
end
assert_equal [], lines(out)
assert_equal [ "moo: option requires an argument -- b" ], lines(err)
end
def test_invoke_simple_with_illegal_opt
out, err = capture_io_while do
assert_raises SystemExit do
simple_cmd.run(%w( -z ))
end
end
assert_equal [], lines(out)
assert_equal [ "moo: illegal option -- z" ], lines(err)
end
def test_invoke_simple_with_opt_with_block
out, err = capture_io_while do
simple_cmd.run(%w( -a 123 ))
end
assert_equal [ 'moo:123', 'Awesome moo!', '', 'aaa=123' ], lines(out)
assert_equal [], lines(err)
end
def test_invoke_nested_without_opts_or_args
out, err = capture_io_while do
assert_raises SystemExit do
nested_cmd.run(%w())
end
end
assert_equal [ ], lines(out)
assert_equal [ 'super: no command given' ], lines(err)
end
def test_invoke_nested_with_correct_command_name
out, err = capture_io_while do
nested_cmd.run(%w( sub ))
end
assert_equal [ 'Sub-awesome!', '', '' ], lines(out)
assert_equal [ ], lines(err)
end
def test_invoke_nested_with_incorrect_command_name
out, err = capture_io_while do
assert_raises SystemExit do
nested_cmd.run(%w( oogabooga ))
end
end
assert_equal [ ], lines(out)
assert_equal [ "super: unknown command 'oogabooga'" ], lines(err)
end
def test_invoke_nested_with_ambiguous_command_name
out, err = capture_io_while do
assert_raises SystemExit do
nested_cmd.run(%w( s ))
end
end
assert_equal [ ], lines(out)
assert_equal [ "super: 's' is ambiguous:", " sink sub" ], lines(err)
end
def test_invoke_nested_with_alias
out, err = capture_io_while do
nested_cmd.run(%w( sup ))
end
assert_equal [ 'Sub-awesome!', '', '' ], lines(out)
assert_equal [ ], lines(err)
end
def test_invoke_nested_with_options_before_command
out, err = capture_io_while do
nested_cmd.run(%w( -a 666 sub ))
end
assert_equal [ 'super:666', 'Sub-awesome!', '', 'aaa=666' ], lines(out)
assert_equal [ ], lines(err)
end
def test_invoke_nested_with_run_block
out, err = capture_io_while do
nested_cmd_with_run_block.run(%w())
end
assert_equal [ 'super' ], lines(out)
assert_equal [ ], lines(err)
out, err = capture_io_while do
nested_cmd_with_run_block.run(%w( sub ))
end
assert_equal [ 'sub' ], lines(out)
assert_equal [ ], lines(err)
end
def test_help_nested
help = nested_cmd.subcommands.find { |cmd| cmd.name == 'sub' }.help
assert help.include?("USAGE\e[0m\e[0m\n \e[32msuper\e[0m \e[32msub\e[0m [options]\n")
end
def test_help_for_bare_cmd
bare_cmd.help
end
def test_help_with_optional_options
cmd = Cri::Command.define do
name 'build'
flag :s, nil, 'short'
flag nil, :long, 'long'
end
help = cmd.help
assert_match(/--long.*-s/m, help)
assert_match(/^\e\[33m --long \e\[0mlong$/, help)
assert_match(/^\e\[33m -s \e\[0mshort$/, help)
end
def test_help_with_multiple_groups
help = nested_cmd.subcommands.find { |cmd| cmd.name == 'sub' }.help
assert_match(/OPTIONS.*OPTIONS FOR SUPER/m, help)
end
def test_modify_with_block_argument
cmd = Cri::Command.define do |c|
c.name 'build'
end
assert_equal 'build', cmd.name
cmd.modify do |c|
c.name 'compile'
end
assert_equal 'compile', cmd.name
end
def test_modify_without_block_argument
cmd = Cri::Command.define do
name 'build'
end
assert_equal 'build', cmd.name
cmd.modify do
name 'compile'
end
assert_equal 'compile', cmd.name
end
def test_new_basic_root
cmd = Cri::Command.new_basic_root.modify do
name 'mytool'
end
# Check option definitions
assert_equal 1, cmd.option_definitions.size
opt_def = cmd.option_definitions.to_a[0]
assert_equal 'help', opt_def[:long]
# Check subcommand
assert_equal 1, cmd.subcommands.size
assert_equal 'help', cmd.subcommands.to_a[0].name
end
def test_define_with_block_argument
cmd = Cri::Command.define do |c|
c.name 'moo'
end
assert_equal 'moo', cmd.name
end
def test_define_without_block_argument
cmd = Cri::Command.define do
name 'moo'
end
assert_equal 'moo', cmd.name
end
def test_define_subcommand_with_block_argument
cmd = bare_cmd
cmd.define_command do |c|
c.name 'baresub'
end
assert_equal 'baresub', cmd.subcommands.to_a[0].name
end
def test_define_subcommand_without_block_argument
cmd = bare_cmd
cmd.define_command do
name 'baresub'
end
assert_equal 'baresub', cmd.subcommands.to_a[0].name
end
def test_backtrace_includes_filename
error = assert_raises RuntimeError do
Cri::Command.define('raise "boom"', 'mycommand.rb')
end
assert_match /mycommand.rb/, error.backtrace.join("\n")
end
def test_hidden_commands_single
cmd = nested_cmd
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'old-and-deprecated'
c.summary 'does stuff the ancient, totally deprecated way'
c.be_hidden
end
refute cmd.help.include?('hidden commands omitted')
assert cmd.help.include?('hidden command omitted')
refute cmd.help.include?('old-and-deprecated')
refute cmd.help(:verbose => true).include?('hidden commands omitted')
refute cmd.help(:verbose => true).include?('hidden command omitted')
assert cmd.help(:verbose => true).include?('old-and-deprecated')
end
def test_hidden_commands_multiple
cmd = nested_cmd
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'first'
c.summary 'does stuff first'
end
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'old-and-deprecated'
c.summary 'does stuff the old, deprecated way'
c.be_hidden
end
subcmd = simple_cmd
cmd.add_command subcmd
subcmd.modify do |c|
c.name 'ancient-and-deprecated'
c.summary 'does stuff the ancient, reallydeprecated way'
c.be_hidden
end
assert cmd.help.include?('hidden commands omitted')
refute cmd.help.include?('hidden command omitted')
refute cmd.help.include?('old-and-deprecated')
refute cmd.help.include?('ancient-and-deprecated')
refute cmd.help(:verbose => true).include?('hidden commands omitted')
refute cmd.help(:verbose => true).include?('hidden command omitted')
assert cmd.help(:verbose => true).include?('old-and-deprecated')
assert cmd.help(:verbose => true).include?('ancient-and-deprecated')
pattern = /ancient-and-deprecated.*first.*old-and-deprecated/m
assert_match(pattern, cmd.help(:verbose => true))
end
def test_run_with_raw_args
cmd = Cri::Command.define do
name 'moo'
run do |opts, args|
puts "args=#{args.join(',')} args.raw=#{args.raw.join(',')}"
end
end
out, err = capture_io_while do
cmd.run(%w( foo -- bar ))
end
assert_equal "args=foo,bar args.raw=foo,--,bar\n", out
end
def test_runner_with_raw_args
cmd = Cri::Command.define do
name 'moo'
runner(Class.new(Cri::CommandRunner) do
def run
puts "args=#{arguments.join(',')} args.raw=#{arguments.raw.join(',')}"
end
end)
end
out, err = capture_io_while do
cmd.run(%w( foo -- bar ))
end
assert_equal "args=foo,bar args.raw=foo,--,bar\n", out
end
end
|
require 'socket'
require 'fastbeans/request'
module Fastbeans
class Connection
MAX_RETRIES=3
attr_reader :socket
def initialize(host, port)
Fastbeans.debug("Connecting to #{host}:#{port}")
@host, @port = host, port
@socket = connect!(@host, @port)
end
def connect!(host, port)
@socket = TCPSocket.new(host, port)
@socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
@socket
end
def get_socket
@socket || connect!(@host, @port)
end
def disconnect!
if @socket
@socket.close rescue nil
@socket = nil
end
end
def reconnect!
disconnect!
connect!(@host, @port)
end
def call(*data)
retries = 0
begin
call_without_retries(data)
rescue Fastbeans::RemoteConnectionFailed => e
Fastbeans.debug(e)
if retries < MAX_RETRIES
Fastbeans.debug("Retrying (#{retries} out of #{MAX_RETRIES} retries)")
retries += 1
begin
reconnect!
rescue => e
raise RemoteConnectionDead, e.message
end
retry
else
raise RemoteConnectionDead, "#{e.message} (#{retries} retries)"
end
end
end
def call_without_retries(data)
perform(data)
rescue IOError, Errno::EPIPE, MessagePack::MalformedFormatError => e
disconnect!
ne = RemoteConnectionFailed.new(e.message)
ne.orig_exc = e
raise ne
rescue Exception
disconnect!
raise
end
def with_socket
yield(get_socket)
end
def perform(data)
Request.new(self).perform(data)
end
end
end
Reconnect on Errno::ECONNREFUSED and Errno::ECONNRESET
require 'socket'
require 'fastbeans/request'
module Fastbeans
class Connection
MAX_RETRIES=3
attr_reader :socket
def initialize(host, port)
Fastbeans.debug("Connecting to #{host}:#{port}")
@host, @port = host, port
@socket = connect!(@host, @port)
end
def connect!(host, port)
@socket = TCPSocket.new(host, port)
@socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
@socket
end
def get_socket
@socket || connect!(@host, @port)
end
def disconnect!
if @socket
@socket.close rescue nil
@socket = nil
end
end
def reconnect!
disconnect!
connect!(@host, @port)
end
def call(*data)
retries = 0
begin
call_without_retries(data)
rescue Fastbeans::RemoteConnectionFailed => e
Fastbeans.debug(e)
if retries < MAX_RETRIES
Fastbeans.debug("Retrying (#{retries} out of #{MAX_RETRIES} retries)")
retries += 1
begin
reconnect!
rescue => e
raise RemoteConnectionDead, e.message
end
retry
else
raise RemoteConnectionDead, "#{e.message} (#{retries} retries)"
end
end
end
def call_without_retries(data)
perform(data)
rescue IOError, Errno::EPIPE, Errno::ECONNREFUSED, Errno::ECONNRESET, MessagePack::MalformedFormatError => e
disconnect!
ne = RemoteConnectionFailed.new(e.message)
ne.orig_exc = e
raise ne
rescue Exception
disconnect!
raise
end
def with_socket
yield(get_socket)
end
def perform(data)
Request.new(self).perform(data)
end
end
end
|
require 'tinder'
require 'slack-notifier'
def listen_to_campfire
notifier = Slack::Notifier.new ENV['SLACK_WEBHOOK_URL']
campfire = Tinder::Campfire.new ENV['CAMPFIRE_SUBDOMAIN'], :token => ENV['CAMPFIRE_TOKEN']
room = campfire.rooms.detect { |_room| _room.id.to_s == ENV['CAMPFIRE_ROOM'] }
room.listen do |message|
user = message.user
if user
ping_data = {
username: "#{user.name} (Bot)",
icon_url: user.avatar_url
}
else
ping_data = {}
end
notifier.ping message.body.to_s, ping_data
end
rescue => e
puts "I have failed!! #{e.message}"
listen_to_campfire
end
listen_to_campfire
Just use user.name as Slack is showing Bot after name
require 'tinder'
require 'slack-notifier'
def listen_to_campfire
notifier = Slack::Notifier.new ENV['SLACK_WEBHOOK_URL']
campfire = Tinder::Campfire.new ENV['CAMPFIRE_SUBDOMAIN'], :token => ENV['CAMPFIRE_TOKEN']
room = campfire.rooms.detect { |_room| _room.id.to_s == ENV['CAMPFIRE_ROOM'] }
room.listen do |message|
user = message.user
if user
ping_data = {
username: user.name,
icon_url: user.avatar_url
}
else
ping_data = {}
end
notifier.ping message.body.to_s, ping_data
end
rescue => e
puts "I have failed!! #{e.message}"
listen_to_campfire
end
listen_to_campfire
|
require 'mini_magick'
module FastenTheSeatBelt
def self.included(base)
base.send(:extend, ClassMethods)
base.send(:include, InstanceMethods)
base.send(:include, MiniMagick)
base.class_eval do
attr_accessor :file
end
end
module ClassMethods
def fasten_the_seat_belt(options={})
# Properties
self.property :filename, :string
self.property :size, :integer
self.property :content_type, :string
self.property :created_at, :datetime
self.property :updated_at, :datetime
self.property :images_are_compressed, :boolean
# Callbacks to manage the file
before_save :save_attributes
after_save :save_file
after_destroy :delete_file_and_directory
# Options
options[:path_prefix] = 'public' unless options[:path_prefix]
options[:thumbnails] ||= {}
if options[:content_types]
self.validates_true_for :file, :logic => lambda { verify_content_type }, :message => "File type is incorrect"
end
options[:content_types] = [options[:content_types]] if options[:content_types] and options[:content_types].class != Array
@@fasten_the_seat_belt = options
end
def table_name
table.to_s
end
def fasten_the_seat_belt_options
@@fasten_the_seat_belt
end
def recreate_thumnails!
each {|object| object.generate_thumbnails! }
true
end
end
module InstanceMethods
# Get file path
#
def path(thumb=nil)
return nil unless self.filename
dir = ("%08d" % self.id).scan(/..../)
basename = self.filename.gsub(/\.(.*)$/, '')
extension = self.filename.gsub(/^(.*)\./, '')
if thumb != nil
filename = basename + '_' + thumb.to_s + '.' + extension
else
filename = self.filename
end
"/files/#{self.class.table_name}/"+dir[0]+"/"+dir[1] + "/" + filename
end
def save_attributes
return false unless @file
# Setup attributes
[:content_type, :size, :filename].each do |attribute|
self.send("#{attribute}=", @file[attribute])
end
end
def save_file
return false unless self.filename and @file
Merb.logger.info "Saving file #{self.filename}..."
# Create directories
create_root_directory
# you can thank Jamis Buck for this: http://www.37signals.com/svn/archives2/id_partitioning.php
dir = ("%08d" % self.id).scan(/..../)
FileUtils.mkdir(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]) unless FileTest.exists?(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0])
FileUtils.mkdir(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]+"/"+dir[1]) unless FileTest.exists?(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]+"/"+dir[1])
destination = self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]+"/"+dir[1] + "/" + self.filename
if File.exists?(@file[:tempfile].path)
FileUtils.mv @file[:tempfile].path, destination
end
generate_thumbnails!
@file = nil
self.images_are_compressed ||= true
end
def create_root_directory
root_directory = self.class.fasten_the_seat_belt_options[:path_prefix] + "/#{self.class.table_name}"
FileUtils.mkdir(root_directory) unless FileTest.exists?(root_directory)
end
def delete_file_and_directory
# delete directory
dir = ("%08d" % self.id).scan(/..../)
FileUtils.rm_rf(self.class.fasten_the_seat_belt_options[:path_prefix]+'/#{self.class.table_name}/'+dir[0]+"/"+dir[1]) if FileTest.exists?(self.class.fasten_the_seat_belt_options[:path_prefix]+'/#{self.class.table_name}/'+dir[0]+"/"+dir[1])
#FileUtils.remove(fasten_the_seat_belt[:path_prefix]+'/pictures/'+dir[0]) if FileTest.exists?(fasten_the_seat_belt[:path_prefix]+'/pictures/'+dir[0])
end
def generate_thumbnails!
dir = ("%08d" % self.id).scan(/..../)
Merb.logger.info "Generate thumbnails... id: #{self.id} path_prefix:#{self.class.fasten_the_seat_belt_options[:path_prefix]} dir0:#{dir[0]} dir1:#{dir[1]} filename:#{self.filename}"
self.class.fasten_the_seat_belt_options[:thumbnails].each_pair do |key, value|
resize_to = value[:size]
quality = value[:quality].to_i
image = MiniMagick::Image.from_file(File.join(Merb.root, (self.class.fasten_the_seat_belt_options[:path_prefix]+ "/#{self.class.table_name}/" + dir[0]+"/"+dir[1] + "/" + self.filename)))
image.resize resize_to
basename = self.filename.gsub(/\.(.*)$/, '')
extension = self.filename.gsub(/^(.*)\./, '')
thumb_filename = self.class.fasten_the_seat_belt_options[:path_prefix]+ "/#{self.class.table_name}/" + dir[0]+"/"+dir[1] + "/" + basename + '_' + key.to_s + '.' + extension
# Delete thumbnail if exists
File.delete(thumb_filename) if File.exists?(thumb_filename)
image.write thumb_filename
next if (self.images_are_compressed == false)
if quality and !["image/jpeg", "image/jpg"].include?(self.content_type)
puts "FastenTheSeatBelt says: Quality setting not supported for #{self.content_type} files"
next
end
if quality and quality < 100
compress_jpeg(thumb_filename, quality)
end
end
end
def verify_content_type
true || self.class.fasten_the_seat_belt_options[:content_types].include?(self.content_type)
end
def dont_compress_now!
@dont_compress_now = true
end
def compress_jpeg(filename, quality)
# puts "FastenTheSeatBelt says: Compressing #{filename} to quality #{quality}"
system("jpegoptim #{filename} -m#{quality} --strip-all")
end
def compress_now!
return false if self.images_are_compressed
self.class.fasten_the_seat_belt_options[:thumbnails].each_pair do |key, value|
resize_to = value[:size]
quality = value[:quality].to_i
if quality and !["image/jpeg", "image/jpg"].include?(self.content_type)
puts "FastenTheSeatBelt says: Quality setting not supported for #{self.content_type} files"
next
end
dir = ("%08d" % self.id).scan(/..../)
basename = self.filename.gsub(/\.(.*)$/, '')
extension = self.filename.gsub(/^(.*)\./, '')
thumb_filename = self.class.fasten_the_seat_belt_options[:path_prefix]+ "/#{self.class.table_name}/" + dir[0]+"/"+dir[1] + "/" + basename + '_' + key.to_s + '.' + extension
if quality and quality < 100
compress_jpeg(thumb_filename, quality)
end
end
self.images_are_compressed = true
self.save
end
end
end
Made a lot of optimization in the flipping effects, now faster and not eating memory, voting is implemented
git-svn-id: 0315d8ac1ac37ae69191aa6d6d67756e396c4929@194 7e50b453-718e-45b4-8b2e-e0b3bf222a20
require 'mini_magick'
module FastenTheSeatBelt
def self.included(base)
base.send(:extend, ClassMethods)
base.send(:include, InstanceMethods)
base.send(:include, MiniMagick)
base.class_eval do
attr_accessor :file
end
end
module ClassMethods
def fasten_the_seat_belt(options={})
# Properties
self.property :filename, :string
self.property :size, :integer
self.property :content_type, :string
self.property :created_at, :datetime
self.property :updated_at, :datetime
self.property :images_are_compressed, :boolean
# Callbacks to manage the file
before_save :save_attributes
after_save :save_file
after_destroy :delete_file_and_directory
# Options
options[:path_prefix] = 'public' unless options[:path_prefix]
options[:thumbnails] ||= {}
if options[:content_types]
self.validates_true_for :file, :logic => lambda { verify_content_type }, :message => "File type is incorrect"
end
options[:content_types] = [options[:content_types]] if options[:content_types] and options[:content_types].class != Array
@@fasten_the_seat_belt = options
end
def table_name
table.to_s
end
def fasten_the_seat_belt_options
@@fasten_the_seat_belt
end
def recreate_thumnails!
each {|object| object.generate_thumbnails! }
true
end
end
module InstanceMethods
# Get file path
#
def path(thumb=nil)
return nil unless self.filename
dir = ("%08d" % self.id).scan(/..../)
basename = self.filename.gsub(/\.(.*)$/, '')
extension = self.filename.gsub(/^(.*)\./, '')
if thumb != nil
filename = basename + '_' + thumb.to_s + '.' + extension
else
filename = self.filename
end
"/files/#{self.class.table_name}/"+dir[0]+"/"+dir[1] + "/" + filename
end
def save_attributes
return false unless @file
# Setup attributes
[:content_type, :size, :filename].each do |attribute|
self.send("#{attribute}=", @file[attribute])
end
end
def save_file
return false unless self.filename and @file
Merb.logger.info "Saving file #{self.filename}..."
# Create directories
create_root_directory
# you can thank Jamis Buck for this: http://www.37signals.com/svn/archives2/id_partitioning.php
dir = ("%08d" % self.id).scan(/..../)
FileUtils.mkdir(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]) unless FileTest.exists?(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0])
FileUtils.mkdir(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]+"/"+dir[1]) unless FileTest.exists?(self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]+"/"+dir[1])
destination = self.class.fasten_the_seat_belt_options[:path_prefix]+"/#{self.class.table_name}/"+dir[0]+"/"+dir[1] + "/" + self.filename
if File.exists?(@file[:tempfile].path)
FileUtils.mv @file[:tempfile].path, destination
end
generate_thumbnails!
@file = nil
self.images_are_compressed ||= true
end
def create_root_directory
root_directory = self.class.fasten_the_seat_belt_options[:path_prefix] + "/#{self.class.table_name}"
FileUtils.mkdir(root_directory) unless FileTest.exists?(root_directory)
end
def delete_file_and_directory
# delete directory
dir = ("%08d" % self.id).scan(/..../)
FileUtils.rm_rf(self.class.fasten_the_seat_belt_options[:path_prefix]+'/#{self.class.table_name}/'+dir[0]+"/"+dir[1]) if FileTest.exists?(self.class.fasten_the_seat_belt_options[:path_prefix]+'/#{self.class.table_name}/'+dir[0]+"/"+dir[1])
#FileUtils.remove(fasten_the_seat_belt[:path_prefix]+'/pictures/'+dir[0]) if FileTest.exists?(fasten_the_seat_belt[:path_prefix]+'/pictures/'+dir[0])
end
def generate_thumbnails!
dir = ("%08d" % self.id).scan(/..../)
Merb.logger.info "Generate thumbnails... id: #{self.id} path_prefix:#{self.class.fasten_the_seat_belt_options[:path_prefix]} dir0:#{dir[0]} dir1:#{dir[1]} filename:#{self.filename}"
self.class.fasten_the_seat_belt_options[:thumbnails].each_pair do |key, value|
resize_to = value[:size]
quality = value[:quality].to_i
image = MiniMagick::Image.from_file(File.join(Merb.root, (self.class.fasten_the_seat_belt_options[:path_prefix]+ "/#{self.class.table_name}/" + dir[0]+"/"+dir[1] + "/" + self.filename)))
image.resize resize_to
basename = self.filename.gsub(/\.(.*)$/, '')
extension = self.filename.gsub(/^(.*)\./, '')
thumb_filename = self.class.fasten_the_seat_belt_options[:path_prefix]+ "/#{self.class.table_name}/" + dir[0]+"/"+dir[1] + "/" + basename + '_' + key.to_s + '.' + extension
# Delete thumbnail if exists
File.delete(thumb_filename) if File.exists?(thumb_filename)
image.write thumb_filename
next if ((self.images_are_compressed == false) || (Merb.env=="test"))
if quality and !["image/jpeg", "image/jpg"].include?(self.content_type)
puts "FastenTheSeatBelt says: Quality setting not supported for #{self.content_type} files"
next
end
if quality and quality < 100
compress_jpeg(thumb_filename, quality)
end
end
end
def verify_content_type
true || self.class.fasten_the_seat_belt_options[:content_types].include?(self.content_type)
end
def dont_compress_now!
@dont_compress_now = true
end
def compress_jpeg(filename, quality)
# puts "FastenTheSeatBelt says: Compressing #{filename} to quality #{quality}"
system("jpegoptim #{filename} -m#{quality} --strip-all")
end
def compress_now!
return false if self.images_are_compressed
self.class.fasten_the_seat_belt_options[:thumbnails].each_pair do |key, value|
resize_to = value[:size]
quality = value[:quality].to_i
if quality and !["image/jpeg", "image/jpg"].include?(self.content_type)
puts "FastenTheSeatBelt says: Quality setting not supported for #{self.content_type} files"
next
end
dir = ("%08d" % self.id).scan(/..../)
basename = self.filename.gsub(/\.(.*)$/, '')
extension = self.filename.gsub(/^(.*)\./, '')
thumb_filename = self.class.fasten_the_seat_belt_options[:path_prefix]+ "/#{self.class.table_name}/" + dir[0]+"/"+dir[1] + "/" + basename + '_' + key.to_s + '.' + extension
if quality and quality < 100
compress_jpeg(thumb_filename, quality)
end
end
self.images_are_compressed = true
self.save
end
end
end |
# coding: utf-8
require "helper"
class TestFilters < JekyllUnitTest
class JekyllFilter
include Jekyll::Filters
attr_accessor :site, :context
def initialize(opts = {})
@site = Jekyll::Site.new(
Jekyll.configuration(opts.merge("skip_config_files" => true))
)
@context = Liquid::Context.new({}, {}, { :site => @site })
end
end
context "filters" do
setup do
@filter = JekyllFilter.new({
"source" => source_dir,
"destination" => dest_dir,
"timezone" => "UTC"
})
@sample_time = Time.utc(2013, 03, 27, 11, 22, 33)
@sample_date = Date.parse("2013-03-27")
@time_as_string = "September 11, 2001 12:46:30 -0000"
@time_as_numeric = 1_399_680_607
@array_of_objects = [
{ "color" => "red", "size" => "large" },
{ "color" => "red", "size" => "medium" },
{ "color" => "blue", "size" => "medium" }
]
end
should "markdownify with simple string" do
assert_equal(
"<p>something <strong>really</strong> simple</p>\n",
@filter.markdownify("something **really** simple")
)
end
context "smartify filter" do
should "convert quotes and typographic characters" do
assert_equal(
"SmartyPants is *not* Markdown",
@filter.smartify("SmartyPants is *not* Markdown")
)
assert_equal(
"“This filter’s test…”",
@filter.smartify(%q{"This filter's test..."})
)
end
should "escapes special characters when configured to do so" do
kramdown = JekyllFilter.new({ :kramdown => { :entity_output => :symbolic } })
assert_equal(
"“This filter’s test…”",
kramdown.smartify(%q{"This filter's test..."})
)
end
should "convert HTML entities to unicode characters" do
assert_equal "’", @filter.smartify("’")
assert_equal "“", @filter.smartify("“")
end
should "allow raw HTML passthrough" do
assert_equal(
"Span HTML is <em>not</em> escaped",
@filter.smartify("Span HTML is <em>not</em> escaped")
)
assert_equal(
"<div>Block HTML is not escaped</div>",
@filter.smartify("<div>Block HTML is not escaped</div>")
)
end
should "escape special characters" do
assert_equal "3 < 4", @filter.smartify("3 < 4")
assert_equal "5 > 4", @filter.smartify("5 > 4")
assert_equal "This & that", @filter.smartify("This & that")
end
end
should "sassify with simple string" do
assert_equal(
"p {\n color: #123456; }\n",
@filter.sassify("$blue:#123456\np\n color: $blue")
)
end
should "scssify with simple string" do
assert_equal(
"p {\n color: #123456; }\n",
@filter.scssify("$blue:#123456; p{color: $blue}")
)
end
should "convert array to sentence string with no args" do
assert_equal "", @filter.array_to_sentence_string([])
end
should "convert array to sentence string with one arg" do
assert_equal "1", @filter.array_to_sentence_string([1])
assert_equal "chunky", @filter.array_to_sentence_string(["chunky"])
end
should "convert array to sentence string with two args" do
assert_equal "1 and 2", @filter.array_to_sentence_string([1, 2])
assert_equal "chunky and bacon", @filter.array_to_sentence_string(%w(chunky bacon))
end
should "convert array to sentence string with multiple args" do
assert_equal "1, 2, 3, and 4", @filter.array_to_sentence_string([1, 2, 3, 4])
assert_equal(
"chunky, bacon, bits, and pieces",
@filter.array_to_sentence_string(%w(chunky bacon bits pieces))
)
end
context "date filters" do
context "with Time object" do
should "format a date with short format" do
assert_equal "27 Mar 2013", @filter.date_to_string(@sample_time)
end
should "format a date with long format" do
assert_equal "27 March 2013", @filter.date_to_long_string(@sample_time)
end
should "format a time with xmlschema" do
assert_equal(
"2013-03-27T11:22:33+00:00",
@filter.date_to_xmlschema(@sample_time)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Wed, 27 Mar 2013 11:22:33 +0000",
@filter.date_to_rfc822(@sample_time)
)
end
should "not modify a time in-place when using filters" do
t = Time.new(2004, 9, 15, 0, 2, 37, "+01:00")
assert_equal 3600, t.utc_offset
@filter.date_to_string(t)
assert_equal 3600, t.utc_offset
end
end
context "with Date object" do
should "format a date with short format" do
assert_equal "27 Mar 2013", @filter.date_to_string(@sample_date)
end
should "format a date with long format" do
assert_equal "27 March 2013", @filter.date_to_long_string(@sample_date)
end
should "format a time with xmlschema" do
assert_equal(
"2013-03-27T00:00:00+00:00",
@filter.date_to_xmlschema(@sample_date)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Wed, 27 Mar 2013 00:00:00 +0000",
@filter.date_to_rfc822(@sample_date)
)
end
end
context "with String object" do
should "format a date with short format" do
assert_equal "11 Sep 2001", @filter.date_to_string(@time_as_string)
end
should "format a date with long format" do
assert_equal "11 September 2001", @filter.date_to_long_string(@time_as_string)
end
should "format a time with xmlschema" do
assert_equal(
"2001-09-11T12:46:30+00:00",
@filter.date_to_xmlschema(@time_as_string)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Tue, 11 Sep 2001 12:46:30 +0000",
@filter.date_to_rfc822(@time_as_string)
)
end
end
context "with a Numeric object" do
should "format a date with short format" do
assert_equal "10 May 2014", @filter.date_to_string(@time_as_numeric)
end
should "format a date with long format" do
assert_equal "10 May 2014", @filter.date_to_long_string(@time_as_numeric)
end
should "format a time with xmlschema" do
assert_match(
"2014-05-10T00:10:07",
@filter.date_to_xmlschema(@time_as_numeric)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Sat, 10 May 2014 00:10:07 +0000",
@filter.date_to_rfc822(@time_as_numeric)
)
end
end
end
should "escape xml with ampersands" do
assert_equal "AT&T", @filter.xml_escape("AT&T")
assert_equal(
"<code>command &lt;filename&gt;</code>",
@filter.xml_escape("<code>command <filename></code>")
)
end
should "not error when xml escaping nil" do
assert_equal "", @filter.xml_escape(nil)
end
should "escape space as plus" do
assert_equal "my+things", @filter.cgi_escape("my things")
end
should "escape special characters" do
assert_equal "hey%21", @filter.cgi_escape("hey!")
end
should "escape space as %20" do
assert_equal "my%20things", @filter.uri_escape("my things")
end
context "jsonify filter" do
should "convert hash to json" do
assert_equal "{\"age\":18}", @filter.jsonify({ :age => 18 })
end
should "convert array to json" do
assert_equal "[1,2]", @filter.jsonify([1, 2])
assert_equal(
"[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]",
@filter.jsonify([{ :name => "Jack" }, { :name => "Smith" }])
)
end
should "convert drop to json" do
@filter.site.read
expected = {
"path" => "_posts/2008-02-02-published.markdown",
"previous" => nil,
"output" => nil,
"content" => "This should be published.\n",
"id" => "/publish_test/2008/02/02/published",
"url" => "/publish_test/2008/02/02/published.html",
"relative_path" => "_posts/2008-02-02-published.markdown",
"collection" => "posts",
"excerpt" => "<p>This should be published.</p>\n",
"draft" => false,
"categories" => [
"publish_test"
],
"layout" => "default",
"title" => "Publish",
"category" => "publish_test",
"date" => "2008-02-02 00:00:00 +0000",
"slug" => "published",
"ext" => ".markdown",
"tags" => []
}
actual = JSON.parse(@filter.jsonify(@filter.site.docs_to_write.first.to_liquid))
next_doc = actual.delete("next")
refute_nil next_doc
assert next_doc.is_a?(Hash), "doc.next should be an object"
assert_equal expected, actual
end
should "convert drop with drops to json" do
@filter.site.read
actual = @filter.jsonify(@filter.site.to_liquid)
assert_equal JSON.parse(actual)["jekyll"], {
"environment" => "development",
"version" => Jekyll::VERSION
}
end
# rubocop:disable Style/StructInheritance
class M < Struct.new(:message)
def to_liquid
[message]
end
end
class T < Struct.new(:name)
def to_liquid
{
"name" => name,
:v => 1,
:thing => M.new({ :kay => "jewelers" }),
:stuff => true
}
end
end
should "call #to_liquid " do
expected = [
{
"name" => "Jeremiah",
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
},
{
"name" => "Smathers",
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
}
]
result = @filter.jsonify([T.new("Jeremiah"), T.new("Smathers")])
assert_equal expected, JSON.parse(result)
end
# rubocop:enable Style/StructInheritance
should "handle hashes with all sorts of weird keys and values" do
my_hash = { "posts" => Array.new(3) { |i| T.new(i) } }
expected = {
"posts" => [
{
"name" => 0,
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
},
{
"name" => 1,
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
},
{
"name" => 2,
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
}
]
}
result = @filter.jsonify(my_hash)
assert_equal expected, JSON.parse(result)
end
end
context "group_by filter" do
should "successfully group array of Jekyll::Page's" do
@filter.site.process
grouping = @filter.group_by(@filter.site.pages, "layout")
grouping.each do |g|
assert(
["default", "nil", ""].include?(g["name"]),
"#{g["name"]} isn't a valid grouping."
)
case g["name"]
when "default"
assert(
g["items"].is_a?(Array),
"The list of grouped items for 'default' is not an Array."
)
assert_equal 5, g["items"].size
when "nil"
assert(
g["items"].is_a?(Array),
"The list of grouped items for 'nil' is not an Array."
)
assert_equal 2, g["items"].size
when ""
assert(
g["items"].is_a?(Array),
"The list of grouped items for '' is not an Array."
)
assert_equal 13, g["items"].size
end
end
end
should "include the size of each grouping" do
grouping = @filter.group_by(@filter.site.pages, "layout")
grouping.each do |g|
p g
assert_equal(
g["items"].size,
g["size"],
"The size property for '#{g["name"]}' doesn't match the size of the Array."
)
end
end
end
context "where filter" do
should "return any input that is not an array" do
assert_equal "some string", @filter.where("some string", "la", "le")
end
should "filter objects in a hash appropriately" do
hash = { "a"=>{ "color"=>"red" }, "b"=>{ "color"=>"blue" } }
assert_equal 1, @filter.where(hash, "color", "red").length
assert_equal [{ "color"=>"red" }], @filter.where(hash, "color", "red")
end
should "filter objects appropriately" do
assert_equal 2, @filter.where(@array_of_objects, "color", "red").length
end
should "filter array properties appropriately" do
hash = {
"a" => { "tags"=>%w(x y) },
"b" => { "tags"=>["x"] },
"c" => { "tags"=>%w(y z) }
}
assert_equal 2, @filter.where(hash, "tags", "x").length
end
should "filter array properties alongside string properties" do
hash = {
"a" => { "tags"=>%w(x y) },
"b" => { "tags"=>"x" },
"c" => { "tags"=>%w(y z) }
}
assert_equal 2, @filter.where(hash, "tags", "x").length
end
should "not match substrings" do
hash = {
"a" => { "category"=>"bear" },
"b" => { "category"=>"wolf" },
"c" => { "category"=>%w(bear lion) }
}
assert_equal 0, @filter.where(hash, "category", "ear").length
end
should "stringify during comparison for compatibility with liquid parsing" do
hash = {
"The Words" => { "rating" => 1.2, "featured" => false },
"Limitless" => { "rating" => 9.2, "featured" => true },
"Hustle" => { "rating" => 4.7, "featured" => true }
}
results = @filter.where(hash, "featured", "true")
assert_equal 2, results.length
assert_equal 9.2, results[0]["rating"]
assert_equal 4.7, results[1]["rating"]
results = @filter.where(hash, "rating", 4.7)
assert_equal 1, results.length
assert_equal 4.7, results[0]["rating"]
end
end
context "where_exp filter" do
should "return any input that is not an array" do
assert_equal "some string", @filter.where_exp("some string", "la", "le")
end
should "filter objects in a hash appropriately" do
hash = { "a"=>{ "color"=>"red" }, "b"=>{ "color"=>"blue" } }
assert_equal 1, @filter.where_exp(hash, "item", "item.color == 'red'").length
assert_equal(
[{ "color"=>"red" }],
@filter.where_exp(hash, "item", "item.color == 'red'")
)
end
should "filter objects appropriately" do
assert_equal(
2,
@filter.where_exp(@array_of_objects, "item", "item.color == 'red'").length
)
end
should "stringify during comparison for compatibility with liquid parsing" do
hash = {
"The Words" => { "rating" => 1.2, "featured" => false },
"Limitless" => { "rating" => 9.2, "featured" => true },
"Hustle" => { "rating" => 4.7, "featured" => true }
}
results = @filter.where_exp(hash, "item", "item.featured == true")
assert_equal 2, results.length
assert_equal 9.2, results[0]["rating"]
assert_equal 4.7, results[1]["rating"]
results = @filter.where_exp(hash, "item", "item.rating == 4.7")
assert_equal 1, results.length
assert_equal 4.7, results[0]["rating"]
end
should "filter with other operators" do
assert_equal [3, 4, 5], @filter.where_exp([ 1, 2, 3, 4, 5 ], "n", "n >= 3")
end
objects = [
{ "id" => "a", "groups" => [1, 2] },
{ "id" => "b", "groups" => [2, 3] },
{ "id" => "c" },
{ "id" => "d", "groups" => [1, 3] }
]
should "filter with the contains operator over arrays" do
results = @filter.where_exp(objects, "obj", "obj.groups contains 1")
assert_equal 2, results.length
assert_equal "a", results[0]["id"]
assert_equal "d", results[1]["id"]
end
should "filter with the contains operator over hash keys" do
results = @filter.where_exp(objects, "obj", "obj contains 'groups'")
assert_equal 3, results.length
assert_equal "a", results[0]["id"]
assert_equal "b", results[1]["id"]
assert_equal "d", results[2]["id"]
end
end
context "sort filter" do
should "raise Exception when input is nil" do
err = assert_raises ArgumentError do
@filter.sort(nil)
end
assert_equal "Cannot sort a null object.", err.message
end
should "return sorted numbers" do
assert_equal [1, 2, 2.2, 3], @filter.sort([3, 2.2, 2, 1])
end
should "return sorted strings" do
assert_equal %w(10 2), @filter.sort(%w(10 2))
assert_equal(
[{ "a" => "10" }, { "a" => "2" }],
@filter.sort([{ "a" => "10" }, { "a" => "2" }], "a")
)
assert_equal %w(FOO Foo foo), @filter.sort(%w(foo Foo FOO))
assert_equal %w(_foo foo foo_), @filter.sort(%w(foo_ _foo foo))
# Cyrillic
assert_equal %w(ВУЗ Вуз вуз), @filter.sort(%w(Вуз вуз ВУЗ))
assert_equal %w(_вуз вуз вуз_), @filter.sort(%w(вуз_ _вуз вуз))
# Hebrew
assert_equal %w(אלף בית), @filter.sort(%w(בית אלף))
end
should "return sorted by property array" do
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }],
@filter.sort([{ "a" => 4 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a")
end
should "return sorted by property array with nils first" do
ary = [{ "a" => 2 }, { "b" => 1 }, { "a" => 1 }]
assert_equal [{ "b" => 1 }, { "a" => 1 }, { "a" => 2 }], @filter.sort(ary, "a")
assert_equal @filter.sort(ary, "a"), @filter.sort(ary, "a", "first")
end
should "return sorted by property array with nils last" do
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "b" => 1 }],
@filter.sort([{ "a" => 2 }, { "b" => 1 }, { "a" => 1 }], "a", "last")
end
end
context "inspect filter" do
should "return a HTML-escaped string representation of an object" do
assert_equal "{"<a>"=>1}", @filter.inspect({ "<a>" => 1 })
end
should "quote strings" do
assert_equal ""string"", @filter.inspect("string")
end
end
context "slugify filter" do
should "return a slugified string" do
assert_equal "q-bert-says", @filter.slugify(" Q*bert says @!#?@!")
end
should "return a slugified string with mode" do
assert_equal "q-bert-says-@!-@!", @filter.slugify(" Q*bert says @!#?@!", "pretty")
end
end
context "push filter" do
should "return a new array with the element pushed to the end" do
assert_equal %w(hi there bernie), @filter.push(%w(hi there), "bernie")
end
end
context "pop filter" do
should "return a new array with the last element popped" do
assert_equal %w(hi there), @filter.pop(%w(hi there bernie))
end
should "allow multiple els to be popped" do
assert_equal %w(hi there bert), @filter.pop(%w(hi there bert and ernie), 2)
end
should "cast string inputs for # into nums" do
assert_equal %w(hi there bert), @filter.pop(%w(hi there bert and ernie), "2")
end
end
context "shift filter" do
should "return a new array with the element removed from the front" do
assert_equal %w(a friendly greeting), @filter.shift(%w(just a friendly greeting))
end
should "allow multiple els to be shifted" do
assert_equal %w(bert and ernie), @filter.shift(%w(hi there bert and ernie), 2)
end
should "cast string inputs for # into nums" do
assert_equal %w(bert and ernie), @filter.shift(%w(hi there bert and ernie), "2")
end
end
context "unshift filter" do
should "return a new array with the element put at the front" do
assert_equal %w(aloha there bernie), @filter.unshift(%w(there bernie), "aloha")
end
end
context "sample filter" do
should "return a random item from the array" do
input = %w(hey there bernie)
assert_includes input, @filter.sample(input)
end
should "allow sampling of multiple values (n > 1)" do
input = %w(hey there bernie)
@filter.sample(input, 2).each do |val|
assert_includes input, val
end
end
end
end
end
Failing test: markdownify a number
# coding: utf-8
require "helper"
class TestFilters < JekyllUnitTest
class JekyllFilter
include Jekyll::Filters
attr_accessor :site, :context
def initialize(opts = {})
@site = Jekyll::Site.new(
Jekyll.configuration(opts.merge("skip_config_files" => true))
)
@context = Liquid::Context.new({}, {}, { :site => @site })
end
end
context "filters" do
setup do
@filter = JekyllFilter.new({
"source" => source_dir,
"destination" => dest_dir,
"timezone" => "UTC"
})
@sample_time = Time.utc(2013, 03, 27, 11, 22, 33)
@sample_date = Date.parse("2013-03-27")
@time_as_string = "September 11, 2001 12:46:30 -0000"
@time_as_numeric = 1_399_680_607
@array_of_objects = [
{ "color" => "red", "size" => "large" },
{ "color" => "red", "size" => "medium" },
{ "color" => "blue", "size" => "medium" }
]
end
should "markdownify with simple string" do
assert_equal(
"<p>something <strong>really</strong> simple</p>\n",
@filter.markdownify("something **really** simple")
)
end
should "markdownify with a number" do
assert_equal(
"<p>404</p>\n",
@filter.markdownify(404)
)
end
context "smartify filter" do
should "convert quotes and typographic characters" do
assert_equal(
"SmartyPants is *not* Markdown",
@filter.smartify("SmartyPants is *not* Markdown")
)
assert_equal(
"“This filter’s test…”",
@filter.smartify(%q{"This filter's test..."})
)
end
should "escapes special characters when configured to do so" do
kramdown = JekyllFilter.new({ :kramdown => { :entity_output => :symbolic } })
assert_equal(
"“This filter’s test…”",
kramdown.smartify(%q{"This filter's test..."})
)
end
should "convert HTML entities to unicode characters" do
assert_equal "’", @filter.smartify("’")
assert_equal "“", @filter.smartify("“")
end
should "allow raw HTML passthrough" do
assert_equal(
"Span HTML is <em>not</em> escaped",
@filter.smartify("Span HTML is <em>not</em> escaped")
)
assert_equal(
"<div>Block HTML is not escaped</div>",
@filter.smartify("<div>Block HTML is not escaped</div>")
)
end
should "escape special characters" do
assert_equal "3 < 4", @filter.smartify("3 < 4")
assert_equal "5 > 4", @filter.smartify("5 > 4")
assert_equal "This & that", @filter.smartify("This & that")
end
should "convert a number to a string" do
assert_equal(
"404",
@filter.smartify(404)
)
end
end
should "sassify with simple string" do
assert_equal(
"p {\n color: #123456; }\n",
@filter.sassify("$blue:#123456\np\n color: $blue")
)
end
should "scssify with simple string" do
assert_equal(
"p {\n color: #123456; }\n",
@filter.scssify("$blue:#123456; p{color: $blue}")
)
end
should "convert array to sentence string with no args" do
assert_equal "", @filter.array_to_sentence_string([])
end
should "convert array to sentence string with one arg" do
assert_equal "1", @filter.array_to_sentence_string([1])
assert_equal "chunky", @filter.array_to_sentence_string(["chunky"])
end
should "convert array to sentence string with two args" do
assert_equal "1 and 2", @filter.array_to_sentence_string([1, 2])
assert_equal "chunky and bacon", @filter.array_to_sentence_string(%w(chunky bacon))
end
should "convert array to sentence string with multiple args" do
assert_equal "1, 2, 3, and 4", @filter.array_to_sentence_string([1, 2, 3, 4])
assert_equal(
"chunky, bacon, bits, and pieces",
@filter.array_to_sentence_string(%w(chunky bacon bits pieces))
)
end
context "date filters" do
context "with Time object" do
should "format a date with short format" do
assert_equal "27 Mar 2013", @filter.date_to_string(@sample_time)
end
should "format a date with long format" do
assert_equal "27 March 2013", @filter.date_to_long_string(@sample_time)
end
should "format a time with xmlschema" do
assert_equal(
"2013-03-27T11:22:33+00:00",
@filter.date_to_xmlschema(@sample_time)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Wed, 27 Mar 2013 11:22:33 +0000",
@filter.date_to_rfc822(@sample_time)
)
end
should "not modify a time in-place when using filters" do
t = Time.new(2004, 9, 15, 0, 2, 37, "+01:00")
assert_equal 3600, t.utc_offset
@filter.date_to_string(t)
assert_equal 3600, t.utc_offset
end
end
context "with Date object" do
should "format a date with short format" do
assert_equal "27 Mar 2013", @filter.date_to_string(@sample_date)
end
should "format a date with long format" do
assert_equal "27 March 2013", @filter.date_to_long_string(@sample_date)
end
should "format a time with xmlschema" do
assert_equal(
"2013-03-27T00:00:00+00:00",
@filter.date_to_xmlschema(@sample_date)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Wed, 27 Mar 2013 00:00:00 +0000",
@filter.date_to_rfc822(@sample_date)
)
end
end
context "with String object" do
should "format a date with short format" do
assert_equal "11 Sep 2001", @filter.date_to_string(@time_as_string)
end
should "format a date with long format" do
assert_equal "11 September 2001", @filter.date_to_long_string(@time_as_string)
end
should "format a time with xmlschema" do
assert_equal(
"2001-09-11T12:46:30+00:00",
@filter.date_to_xmlschema(@time_as_string)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Tue, 11 Sep 2001 12:46:30 +0000",
@filter.date_to_rfc822(@time_as_string)
)
end
end
context "with a Numeric object" do
should "format a date with short format" do
assert_equal "10 May 2014", @filter.date_to_string(@time_as_numeric)
end
should "format a date with long format" do
assert_equal "10 May 2014", @filter.date_to_long_string(@time_as_numeric)
end
should "format a time with xmlschema" do
assert_match(
"2014-05-10T00:10:07",
@filter.date_to_xmlschema(@time_as_numeric)
)
end
should "format a time according to RFC-822" do
assert_equal(
"Sat, 10 May 2014 00:10:07 +0000",
@filter.date_to_rfc822(@time_as_numeric)
)
end
end
end
should "escape xml with ampersands" do
assert_equal "AT&T", @filter.xml_escape("AT&T")
assert_equal(
"<code>command &lt;filename&gt;</code>",
@filter.xml_escape("<code>command <filename></code>")
)
end
should "not error when xml escaping nil" do
assert_equal "", @filter.xml_escape(nil)
end
should "escape space as plus" do
assert_equal "my+things", @filter.cgi_escape("my things")
end
should "escape special characters" do
assert_equal "hey%21", @filter.cgi_escape("hey!")
end
should "escape space as %20" do
assert_equal "my%20things", @filter.uri_escape("my things")
end
context "jsonify filter" do
should "convert hash to json" do
assert_equal "{\"age\":18}", @filter.jsonify({ :age => 18 })
end
should "convert array to json" do
assert_equal "[1,2]", @filter.jsonify([1, 2])
assert_equal(
"[{\"name\":\"Jack\"},{\"name\":\"Smith\"}]",
@filter.jsonify([{ :name => "Jack" }, { :name => "Smith" }])
)
end
should "convert drop to json" do
@filter.site.read
expected = {
"path" => "_posts/2008-02-02-published.markdown",
"previous" => nil,
"output" => nil,
"content" => "This should be published.\n",
"id" => "/publish_test/2008/02/02/published",
"url" => "/publish_test/2008/02/02/published.html",
"relative_path" => "_posts/2008-02-02-published.markdown",
"collection" => "posts",
"excerpt" => "<p>This should be published.</p>\n",
"draft" => false,
"categories" => [
"publish_test"
],
"layout" => "default",
"title" => "Publish",
"category" => "publish_test",
"date" => "2008-02-02 00:00:00 +0000",
"slug" => "published",
"ext" => ".markdown",
"tags" => []
}
actual = JSON.parse(@filter.jsonify(@filter.site.docs_to_write.first.to_liquid))
next_doc = actual.delete("next")
refute_nil next_doc
assert next_doc.is_a?(Hash), "doc.next should be an object"
assert_equal expected, actual
end
should "convert drop with drops to json" do
@filter.site.read
actual = @filter.jsonify(@filter.site.to_liquid)
assert_equal JSON.parse(actual)["jekyll"], {
"environment" => "development",
"version" => Jekyll::VERSION
}
end
# rubocop:disable Style/StructInheritance
class M < Struct.new(:message)
def to_liquid
[message]
end
end
class T < Struct.new(:name)
def to_liquid
{
"name" => name,
:v => 1,
:thing => M.new({ :kay => "jewelers" }),
:stuff => true
}
end
end
should "call #to_liquid " do
expected = [
{
"name" => "Jeremiah",
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
},
{
"name" => "Smathers",
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
}
]
result = @filter.jsonify([T.new("Jeremiah"), T.new("Smathers")])
assert_equal expected, JSON.parse(result)
end
# rubocop:enable Style/StructInheritance
should "handle hashes with all sorts of weird keys and values" do
my_hash = { "posts" => Array.new(3) { |i| T.new(i) } }
expected = {
"posts" => [
{
"name" => 0,
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
},
{
"name" => 1,
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
},
{
"name" => 2,
"v" => 1,
"thing" => [
{
"kay" => "jewelers"
}
],
"stuff" => true
}
]
}
result = @filter.jsonify(my_hash)
assert_equal expected, JSON.parse(result)
end
end
context "group_by filter" do
should "successfully group array of Jekyll::Page's" do
@filter.site.process
grouping = @filter.group_by(@filter.site.pages, "layout")
grouping.each do |g|
assert(
["default", "nil", ""].include?(g["name"]),
"#{g["name"]} isn't a valid grouping."
)
case g["name"]
when "default"
assert(
g["items"].is_a?(Array),
"The list of grouped items for 'default' is not an Array."
)
assert_equal 5, g["items"].size
when "nil"
assert(
g["items"].is_a?(Array),
"The list of grouped items for 'nil' is not an Array."
)
assert_equal 2, g["items"].size
when ""
assert(
g["items"].is_a?(Array),
"The list of grouped items for '' is not an Array."
)
assert_equal 13, g["items"].size
end
end
end
should "include the size of each grouping" do
grouping = @filter.group_by(@filter.site.pages, "layout")
grouping.each do |g|
p g
assert_equal(
g["items"].size,
g["size"],
"The size property for '#{g["name"]}' doesn't match the size of the Array."
)
end
end
end
context "where filter" do
should "return any input that is not an array" do
assert_equal "some string", @filter.where("some string", "la", "le")
end
should "filter objects in a hash appropriately" do
hash = { "a"=>{ "color"=>"red" }, "b"=>{ "color"=>"blue" } }
assert_equal 1, @filter.where(hash, "color", "red").length
assert_equal [{ "color"=>"red" }], @filter.where(hash, "color", "red")
end
should "filter objects appropriately" do
assert_equal 2, @filter.where(@array_of_objects, "color", "red").length
end
should "filter array properties appropriately" do
hash = {
"a" => { "tags"=>%w(x y) },
"b" => { "tags"=>["x"] },
"c" => { "tags"=>%w(y z) }
}
assert_equal 2, @filter.where(hash, "tags", "x").length
end
should "filter array properties alongside string properties" do
hash = {
"a" => { "tags"=>%w(x y) },
"b" => { "tags"=>"x" },
"c" => { "tags"=>%w(y z) }
}
assert_equal 2, @filter.where(hash, "tags", "x").length
end
should "not match substrings" do
hash = {
"a" => { "category"=>"bear" },
"b" => { "category"=>"wolf" },
"c" => { "category"=>%w(bear lion) }
}
assert_equal 0, @filter.where(hash, "category", "ear").length
end
should "stringify during comparison for compatibility with liquid parsing" do
hash = {
"The Words" => { "rating" => 1.2, "featured" => false },
"Limitless" => { "rating" => 9.2, "featured" => true },
"Hustle" => { "rating" => 4.7, "featured" => true }
}
results = @filter.where(hash, "featured", "true")
assert_equal 2, results.length
assert_equal 9.2, results[0]["rating"]
assert_equal 4.7, results[1]["rating"]
results = @filter.where(hash, "rating", 4.7)
assert_equal 1, results.length
assert_equal 4.7, results[0]["rating"]
end
end
context "where_exp filter" do
should "return any input that is not an array" do
assert_equal "some string", @filter.where_exp("some string", "la", "le")
end
should "filter objects in a hash appropriately" do
hash = { "a"=>{ "color"=>"red" }, "b"=>{ "color"=>"blue" } }
assert_equal 1, @filter.where_exp(hash, "item", "item.color == 'red'").length
assert_equal(
[{ "color"=>"red" }],
@filter.where_exp(hash, "item", "item.color == 'red'")
)
end
should "filter objects appropriately" do
assert_equal(
2,
@filter.where_exp(@array_of_objects, "item", "item.color == 'red'").length
)
end
should "stringify during comparison for compatibility with liquid parsing" do
hash = {
"The Words" => { "rating" => 1.2, "featured" => false },
"Limitless" => { "rating" => 9.2, "featured" => true },
"Hustle" => { "rating" => 4.7, "featured" => true }
}
results = @filter.where_exp(hash, "item", "item.featured == true")
assert_equal 2, results.length
assert_equal 9.2, results[0]["rating"]
assert_equal 4.7, results[1]["rating"]
results = @filter.where_exp(hash, "item", "item.rating == 4.7")
assert_equal 1, results.length
assert_equal 4.7, results[0]["rating"]
end
should "filter with other operators" do
assert_equal [3, 4, 5], @filter.where_exp([ 1, 2, 3, 4, 5 ], "n", "n >= 3")
end
objects = [
{ "id" => "a", "groups" => [1, 2] },
{ "id" => "b", "groups" => [2, 3] },
{ "id" => "c" },
{ "id" => "d", "groups" => [1, 3] }
]
should "filter with the contains operator over arrays" do
results = @filter.where_exp(objects, "obj", "obj.groups contains 1")
assert_equal 2, results.length
assert_equal "a", results[0]["id"]
assert_equal "d", results[1]["id"]
end
should "filter with the contains operator over hash keys" do
results = @filter.where_exp(objects, "obj", "obj contains 'groups'")
assert_equal 3, results.length
assert_equal "a", results[0]["id"]
assert_equal "b", results[1]["id"]
assert_equal "d", results[2]["id"]
end
end
context "sort filter" do
should "raise Exception when input is nil" do
err = assert_raises ArgumentError do
@filter.sort(nil)
end
assert_equal "Cannot sort a null object.", err.message
end
should "return sorted numbers" do
assert_equal [1, 2, 2.2, 3], @filter.sort([3, 2.2, 2, 1])
end
should "return sorted strings" do
assert_equal %w(10 2), @filter.sort(%w(10 2))
assert_equal(
[{ "a" => "10" }, { "a" => "2" }],
@filter.sort([{ "a" => "10" }, { "a" => "2" }], "a")
)
assert_equal %w(FOO Foo foo), @filter.sort(%w(foo Foo FOO))
assert_equal %w(_foo foo foo_), @filter.sort(%w(foo_ _foo foo))
# Cyrillic
assert_equal %w(ВУЗ Вуз вуз), @filter.sort(%w(Вуз вуз ВУЗ))
assert_equal %w(_вуз вуз вуз_), @filter.sort(%w(вуз_ _вуз вуз))
# Hebrew
assert_equal %w(אלף בית), @filter.sort(%w(בית אלף))
end
should "return sorted by property array" do
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }],
@filter.sort([{ "a" => 4 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a")
end
should "return sorted by property array with nils first" do
ary = [{ "a" => 2 }, { "b" => 1 }, { "a" => 1 }]
assert_equal [{ "b" => 1 }, { "a" => 1 }, { "a" => 2 }], @filter.sort(ary, "a")
assert_equal @filter.sort(ary, "a"), @filter.sort(ary, "a", "first")
end
should "return sorted by property array with nils last" do
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "b" => 1 }],
@filter.sort([{ "a" => 2 }, { "b" => 1 }, { "a" => 1 }], "a", "last")
end
end
context "inspect filter" do
should "return a HTML-escaped string representation of an object" do
assert_equal "{"<a>"=>1}", @filter.inspect({ "<a>" => 1 })
end
should "quote strings" do
assert_equal ""string"", @filter.inspect("string")
end
end
context "slugify filter" do
should "return a slugified string" do
assert_equal "q-bert-says", @filter.slugify(" Q*bert says @!#?@!")
end
should "return a slugified string with mode" do
assert_equal "q-bert-says-@!-@!", @filter.slugify(" Q*bert says @!#?@!", "pretty")
end
end
context "push filter" do
should "return a new array with the element pushed to the end" do
assert_equal %w(hi there bernie), @filter.push(%w(hi there), "bernie")
end
end
context "pop filter" do
should "return a new array with the last element popped" do
assert_equal %w(hi there), @filter.pop(%w(hi there bernie))
end
should "allow multiple els to be popped" do
assert_equal %w(hi there bert), @filter.pop(%w(hi there bert and ernie), 2)
end
should "cast string inputs for # into nums" do
assert_equal %w(hi there bert), @filter.pop(%w(hi there bert and ernie), "2")
end
end
context "shift filter" do
should "return a new array with the element removed from the front" do
assert_equal %w(a friendly greeting), @filter.shift(%w(just a friendly greeting))
end
should "allow multiple els to be shifted" do
assert_equal %w(bert and ernie), @filter.shift(%w(hi there bert and ernie), 2)
end
should "cast string inputs for # into nums" do
assert_equal %w(bert and ernie), @filter.shift(%w(hi there bert and ernie), "2")
end
end
context "unshift filter" do
should "return a new array with the element put at the front" do
assert_equal %w(aloha there bernie), @filter.unshift(%w(there bernie), "aloha")
end
end
context "sample filter" do
should "return a random item from the array" do
input = %w(hey there bernie)
assert_includes input, @filter.sample(input)
end
should "allow sampling of multiple values (n > 1)" do
input = %w(hey there bernie)
@filter.sample(input, 2).each do |val|
assert_includes input, val
end
end
end
end
end
|
require 'rake'
require 'rake/tasklib'
module FastlyNsq
class RakeTask < Rake::TaskLib
attr_accessor :name, :channel, :topics
attr_writer :listener
def initialize(*args, &task_block)
@name = args.shift || :begin_listening
add_rake_task_description_if_one_needed
task(name, *args) do |_, task_args|
RakeFileUtils.send(:verbose, verbose) do
if block_given?
yield(*[self, task_args].slice(0, task_block.arity))
end
@channel ||= require_arg :channel, task_args
@topics ||= require_arg :topics, task_args
@listener ||= task_args[:listener]
listen_to_configured_topics
end
end
end
private
def listen_to_configured_topics
topic_per_thread do |topic, processor|
logger.info "Listening to queue, topic:'#{topic}' and channel: '#{channel}'"
listener.listen_to topic: topic,
channel: channel,
processor: processor
logger.info "... done listening on topic:'#{topic}' and channel: '#{channel}'."
end
end
def require_arg(arg, arg_list)
arg_list.fetch(arg) { raise ArgumentError, "required configuration '#{arg}' is missing." }
end
def add_rake_task_description_if_one_needed
unless ::Rake.application.last_description
desc 'Listen to NSQ on topic using channel'
end
end
def topic_per_thread
topics.each do |(topic, processor)|
Thread.new do
yield topic, processor
end
end
non_main_threads = (Thread.list - [Thread.main])
non_main_threads.map(&:join)
end
def listener
@listener || FastlyNsq::Listener
end
def logger
@logger || FastlyNsq.logger || Logger.new(STDOUT)
end
end
end
Threads in the style of 8b55560
require 'rake'
require 'rake/tasklib'
module FastlyNsq
class RakeTask < Rake::TaskLib
attr_accessor :name, :channel, :topics
attr_writer :listener
def initialize(*args, &task_block)
@name = args.shift || :begin_listening
add_rake_task_description_if_one_needed
task(name, *args) do |_, task_args|
RakeFileUtils.send(:verbose, verbose) do
if block_given?
yield(*[self, task_args].slice(0, task_block.arity))
end
@channel ||= require_arg :channel, task_args
@topics ||= require_arg :topics, task_args
@listener ||= task_args[:listener]
listen_to_configured_topics
end
end
end
private
def listen_to_configured_topics
topic_per_thread do |topic, processor|
logger.info "Listening to queue, topic:'#{topic}' and channel: '#{channel}'"
listener.listen_to topic: topic,
channel: channel,
processor: processor
logger.info "... done listening on topic:'#{topic}' and channel: '#{channel}'."
end
end
def require_arg(arg, arg_list)
arg_list.fetch(arg) { raise ArgumentError, "required configuration '#{arg}' is missing." }
end
def add_rake_task_description_if_one_needed
unless ::Rake.application.last_description
desc 'Listen to NSQ on topic using channel'
end
end
def topic_per_thread
listener_threads = []
topics.each do |(topic, processor)|
thread = Thread.new do
yield topic, processor
end
thread.abort_on_exception = true
listener_threads << thread
end
listener_threads.map(&:join)
end
def listener
@listener || FastlyNsq::Listener
end
def logger
@logger || FastlyNsq.logger || Logger.new(STDOUT)
end
end
end
|
Added FileProcessor module
# -*- encoding : utf-8 -*-
module Fclay
module FileProcessor
LOCAL_URL = "/system/local_storage"
LOCAL_FOLDER = "/public#{LOCAL_URL}"
attr_accessor :file
def self.delete_files files
files = [files] unless files.class == Array
files.each do |f|
FileUtils.rm f
end
end
def self.upload type,id
type = type.constantize
uploading_object = type.find(id)
return if uploading_object.file_status == "in_remote_storage"
content_type = uploading_object.try(:content_type)
bucket = bucket_object
obj = bucket.object(uploading_object.remote_file_path)
obj.put({
body: File.read(uploading_object.local_file_path),
acl: "public-read",
content_type: uploading_object.content_type
})
if uploading_object.update_attribute(:file_status, 'in_remote_storage')
uploading_object.delete_local_files
end
uploading_object.try(:uploaded)
end
def check_file
errors.add(:file, 'must be present') if id.blank? && @file.blank?
self.content_type = @file.content_type
end
def file_size_mb
"#{((self.file_size >> 10).to_f / 1024).round(2)} Mb" if self.file_size
end
def file_url_style_sync
file_url(:sync)
end
def file_url(style=nil)
case file_status
when "in_local_storage"
local_file_url(style)
when "in_remote_storage"
remote_file_url(style)
end
end
def remote_file_url(style=nil)
"http://#{ENV['crm_s3_bucket']}.s3.amazonaws.com/#{remote_file_path(style)}"
end
def local_file_path(style=nil)
local_file_dir(style) + "/" + file_name
end
def local_file_url(style=nil)
url = "http://#{ENV["crm_assets_domain"]}"
url += ":3000" if Rails.env.development?
url += "#{LOCAL_URL}/#{self.class.name.tableize}"
url += "/#{style.to_s}" if style && style != :nil
url += "/#{file_name}"
url
end
def short_local_file_url(style=nil)
end
def local_file_dir(style=nil)
dir = "#{Rails.root.to_s + LOCAL_FOLDER}/#{self.class.name.tableize}"
dir += "/#{style.to_s}" if style && style != :nil
dir
end
def remote_file_path(style=nil)
path = ""
path += "#{self.class.name.tableize}"
path += "/#{file_name}"
path
end
def delete_tmp_file
FileUtils.rm(@file.try(:path) || @file[:path],{:force => true}) if @file
@file = nil
end
def create_dirs
(self.class.name.constantize.try(:styles) || [nil]).each do |style|
FileUtils.mkdir_p(local_file_dir(style))
end
end
def process_file
return unless @file
if self.file_status == 'in_remote_storage'
self.class.name.constantize::STYLES.each do |style|
S3.delay(:queue => "backend").delete_s3_file s3_file_path(style)
end
self.file_status = 'new'
end
create_dirs
ext = self.class.name.constantize.try(:extension)
unless ext
filename_part = @file.original_filename.split(".")
ext = ".#{filename_part.last}" if filename_part.size > 1
end
file_name = try(:generate_filename)
file_name = SecureRandom.hex unless file_name
self.file_name = file_name + ext
FileUtils.mv(@file.try(:path) || @file[:path],local_file_path)
`chmod 0755 #{local_file_path}`
delete_tmp_file
set_file_size
self.file_status = 'in_local_storage'
end
def delete_local_files
begin
FileUtils.rm(local_file_path,{:force => true})
rescue
Rails.logger.info "Deleting Media #{id} sync file not found"
end
end
def set_file_size style=:nil
self.file_size = File.size local_file_path(style)
end
def self.resolve_file_url navigation_complex_id,type,file_name,style=nil
return "" if file_name.nil? || type.nil?
path = "http://s3.amazonaws.com/#{BUCKET_NAME}"
path += "/navigation_complex/#{navigation_complex_id}" if navigation_complex_id
path += "/#{type}"
path += "/#{style.to_s}" if style
path += "/#{file_name}"
path
end
def self.bucket_object
s3 = Aws::S3::Resource.new
s3.bucket(ENV['crm_s3_bucket'])
end
end
end
|
require 'feedzirra'
require 'nokogiri'
require 'active_support'
require 'sanitize'
require 'uri'
module Feedzirra
module FeedzirraParserExtensions
# mix this into feed, or whatever else has an entries object
### Method to find base url
def base_url
# could use xml:base, but i think that data is lost
url || feed_url
end
def base_url_merge(uri_or_string)
self.base_url.merge(uri_or_string)
end
def entries_with_absolute_img_src
entries.map do |e|
nodes = Nokogiri::HTML.parse(e.content)
ge = GenericEntry.create_from_entry(e)
html.css("img").each do |node|
node['src'] = base_url_merge(node['src']) if node['src']
end
# Might have to mark this as safe on the rails side?
ge.content = nodes.to_s
ge
end
end
###
### Methods for where_entries
###
# phtase search, but no word boundary
def match_author_exact(name)
name = name.downcase || ""
self.entries.find_all do |entry|
author = entry.author.downcase || ""
author.include?(name)
end
end
# phrase search
def match_title(match_string)
text = match_string.downcase || ""
re = Regexp.new(/\b#{text}/i)
entries.find_all do |entry|
clean_title = entry.title ? entry.title.downcase : ""
clean_title =~ re
end
end
# any of the words
def match_title_any_word(match_string)
text = match_string.downcase || ""
words = text.split()
res = words.map { |w| Regexp.new("\b#{w}") }
entries.find_all do |entry|
clean_title = entry.title ? entry.title.downcase : ""
matches = false
res.each do |re|
matches = matches || clean_title =~ re
end
matches
end
end
# all of the words
def match_title_all_words(match_string)
text = match_string.downcase || ""
words = text.split()
res = words.map { |w| Regexp.new("\b#{w}") }
entries.find_all do |entry|
clean_title = entry.title ? entry.title.downcase : ""
matches = true
res.each do |re|
matches = matches && clean_title =~ re
end
matches
end
end
# phrase, no word boundary
def match_text_exact(match_string)
text = match_string.downcase || ""
entries.find_all do |entry|
title, summary, content = cleaned_content(entry)
title.include?(text) ||
summary.include?(text) ||
content.include?(text)
end
end
# phrase
def match_text(match_string)
text = match_string.downcase || ""
re = Regexp.new(/\b#{text}/i)
entries.find_all do |entry|
title, summary, content = cleaned_content(entry)
title =~ re ||
Nokogiri::HTML(summary).content =~ re ||
Nokogiri::HTML(content).content =~ re
end
end
# any word
def match_text_any_word
end
def match_text_all_words
end
def entries_with_images(*args)
entries.find_all do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
html.search("img").length > 0
end
end
def entries_with_links(*args)
entries.find_all do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
html.search("a[href]").length > 0
end
end
def entries_randomly(frequency)
return entries if frequency >= 1
entries.find_all do |entry|
Random.rand < frequency
end
end
def where_entries(options = {})
return self if options == {}
options = options.with_indifferent_access
entries = self.entries
if options['title']
entries = match_title(options['title'])
end
if options['text']
entries = match_text(options['text'])
end
if options['author']
entries = match_author_exact(options['author'])
end
if options['has_image']
entries = entries_with_images
end
if options['has_link']
entries = entries_with_links
end
if options['has_attachment']
entries = entries.find_all do |entry|
# TODO
entry
end
end
if options['random']
entries = entries_randomly(options['random'])
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
###
### Methods for where_entries_not
###
def where_entries_not(options = {})
return self if options == {}
options = options.with_indifferent_access
entries = self.entries
if options['text']
entries = entries.reject do |entry|
title = entry.title ? entry.title.downcase : ""
summary = entry.summary ? entry.summary.downcase : ""
content = entry.content ? entry.content.downcase : ""
text = options['text'].downcase || ""
title.include?(text) ||
summary.include?(text) ||
content.include?(text)
end
end
if options['author']
entries = entries.reject do |entry|
author = entry.author.downcase || ""
text = options['author'].downcase || ""
author.include?(text)
end
end
if options['has_image']
entries = entries.reject do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
html.search("img").length > 0
end
end
if options['has_link']
entries = entries.reject do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
links = html.search("a[href]").length > 0
end
end
if options['has_attachment']
entries = entries.send(method) do |entry|
# TODO
entry
end
end
if options['random']
entries = entries_randomly(1 - options['random'])
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
def map_entries(options = {})
return self if options = {}
options = options.with_indifferent_access
entries = self.entries
if options['images']
entries = entries.map do |entry|
title, summary, content = cleaned_content(entry)
ge = GenericEntry.create_from_entry(entry)
ge.content = Sanitize.clean(content, :elements => ['img'])
ge
end
end
if options['links']
entries = entries.map do |entry|
title, summary, content = cleaned_content(entry)
ge = GenericEntry.create_from_entry(entry)
ge.content = Sanitize.clean(content, :elements => ['a'])
ge
end
end
if options['attachments']
# TODO
end
if options['audio']
# TODO
end
if options['video']
# TODO
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
def remove_entries(options = {})
return self if options = {}
options = options.with_indifferent_access
entries = self.entries
if options['images']
end
if options['links']
end
if options['attachments']
end
if options['audio']
end
if options['video']
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
### Private methods
private
def cleaned_content(entry)
title = entry.title ? entry.title.downcase : ""
summary = entry.summary ? entry.summary.downcase : ""
content = entry.content ? entry.content.downcase : ""
return title, summary, content
end
end
module Parser
class GenericParser
# Not really a parser, just an object that looks like a
# Feedzirra::Parser::XX object
# TODO: what about etags, last modified, etc?
# TODO: if it's filtered, then checking for updates will be different
# I think you have to keep all the individal feeds'
# etags and last modified times around in a separate
# data structure and override the methods that check for updates
# include ::FeedZirra::FeedUtilities
# include ::FeedZirra::FeedzirraParserExtensions
PARSER_ATTRIBUTES = [:title, :url, :feed_url, :entries, :etag,
:last_modified]
include FeedUtilities
include FeedzirraParserExtensions
attr_accessor :title, :url, :feed_url, :entries, :etag, :last_modified
def initialize(title, url, entries)
self.url = url
self.title = title
# ensure this is an Array, or you can't do silly stuff like size()
self.entries = entries.to_a
end
end
class GenericEntry
INSTANCE_VARIABLES = ["@title", "@name", "@content", "@url", "@author",
"@summary", "@published", "@entry_id", "@updated", "@categories",
"@links"]
include FeedEntryUtilities
attr_accessor :title, :name, :content, :url, :author, :summary,
:published, :entry_id, :updated, :categories, :links
def self.create_from_entry(entry)
ge = GenericEntry.new
entry.instance_variables.each do |iv|
# only set attributes GenericEntries have.
if INSTANCE_VARIABLES.include?(iv)
value = entry.instance_variable_get(iv)
ge.instance_variable_set(iv, value)
end
end
end
end
end
end
# Mix in with Feedzirra parsers
# Or if you switch backends from Feedzirra you can mix in appropriately
[
Feedzirra::Parser::Atom, Feedzirra::Parser::AtomFeedBurner,
Feedzirra::Parser::ITunesRSS, Feedzirra::Parser::RSS
].each do |klass|
klass.class_eval do
include Feedzirra::FeedzirraParserExtensions
end
end
add phrase, any, all words search to text
require 'feedzirra'
require 'nokogiri'
require 'active_support'
require 'sanitize'
require 'uri'
module Feedzirra
module FeedzirraParserExtensions
# mix this into feed, or whatever else has an entries object
### Method to find base url
def base_url
# could use xml:base, but i think that data is lost
url || feed_url
end
def base_url_merge(uri_or_string)
self.base_url.merge(uri_or_string)
end
def entries_with_absolute_img_src
entries.map do |e|
nodes = Nokogiri::HTML.parse(e.content)
ge = GenericEntry.create_from_entry(e)
html.css("img").each do |node|
node['src'] = base_url_merge(node['src']) if node['src']
end
# Might have to mark this as safe on the rails side?
ge.content = nodes.to_s
ge
end
end
###
### Methods for where_entries
###
# phtase search, but no word boundary
def match_author_exact(name)
name = name.downcase || ""
self.entries.find_all do |entry|
author = entry.author.downcase || ""
author.include?(name)
end
end
# phrase search
def match_title(match_string)
text = match_string.downcase || ""
re = Regexp.new(/\b#{text}/i)
entries.find_all do |entry|
clean_title = entry.title ? entry.title.downcase : ""
clean_title =~ re
end
end
# any of the words
def match_title_any_word(match_string)
text = match_string.downcase || ""
words = text.split
res = words.map { |w| Regexp.new(/\b#{w}/i) }
entries.find_all do |entry|
clean_title = entry.title ? entry.title.downcase : ""
matches = false
res.each do |re|
matches = matches || clean_title =~ re
end
matches
end
end
# all of the words
def match_title_all_words(match_string)
text = match_string.downcase || ""
words = text.split
res = words.map { |w| Regexp.new(/\b#{w}/i) }
entries.find_all do |entry|
clean_title = entry.title ? entry.title.downcase : ""
matches = true
res.each do |re|
matches = matches && clean_title =~ re
end
matches
end
end
# phrase, no word boundary
def match_text_exact(match_string)
text = match_string.downcase || ""
entries.find_all do |entry|
title, summary, content = cleaned_content(entry)
title.include?(text) ||
summary.include?(text) ||
content.include?(text)
end
end
# phrase
def match_text(match_string)
text = match_string.downcase || ""
re = Regexp.new(/\b#{text}/i)
entries.find_all do |entry|
title, summary, content = cleaned_content(entry)
title =~ re ||
Nokogiri::HTML(summary).content =~ re ||
Nokogiri::HTML(content).content =~ re
end
end
# any word
def match_text_any_word(match_string)
text = match_string.downcase || ""
words = text.split
res = words.map { |w| Regexp.new(/\b#{w}/i) }
entries.find_all do |entry|
title, summary, content = cleaned_content(entry)
matches = false
res.each do |re|
this_re_matches = title =~ re ||
Nokogiri::HTML(summary).content =~ re ||
Nokogiri::HTML(content).content =~ re
matches = matches || this_re_matches
end
matches
end
end
def match_text_all_words(match_string)
text = match_string.downcase || ""
words = text.split
res = words.map { |w| Regexp.new(/\b#{w}/i) }
entries.find_all do |entry|
title, summary, content = cleaned_content(entry)
matches = true
res.each do |re|
this_re_matches = title =~ re ||
Nokogiri::HTML(summary).content =~ re ||
Nokogiri::HTML(content).content =~ re
matches = matches && this_re_matches
end
matches
end
end
def entries_with_images(*args)
entries.find_all do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
html.search("img").length > 0
end
end
def entries_with_links(*args)
entries.find_all do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
html.search("a[href]").length > 0
end
end
def entries_randomly(frequency)
return entries if frequency >= 1
entries.find_all do |entry|
Random.rand < frequency
end
end
def where_entries(options = {})
return self if options == {}
options = options.with_indifferent_access
entries = self.entries
if options['title']
entries = match_title(options['title'])
end
if options['text']
entries = match_text(options['text'])
end
if options['author']
entries = match_author_exact(options['author'])
end
if options['has_image']
entries = entries_with_images
end
if options['has_link']
entries = entries_with_links
end
if options['has_attachment']
entries = entries.find_all do |entry|
# TODO
entry
end
end
if options['random']
entries = entries_randomly(options['random'])
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
###
### Methods for where_entries_not
###
def where_entries_not(options = {})
return self if options == {}
options = options.with_indifferent_access
entries = self.entries
if options['text']
entries = entries.reject do |entry|
title = entry.title ? entry.title.downcase : ""
summary = entry.summary ? entry.summary.downcase : ""
content = entry.content ? entry.content.downcase : ""
text = options['text'].downcase || ""
title.include?(text) ||
summary.include?(text) ||
content.include?(text)
end
end
if options['author']
entries = entries.reject do |entry|
author = entry.author.downcase || ""
text = options['author'].downcase || ""
author.include?(text)
end
end
if options['has_image']
entries = entries.reject do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
html.search("img").length > 0
end
end
if options['has_link']
entries = entries.reject do |entry|
begin
html = Nokogiri::HTML(entry.content)
rescue
return true
end
links = html.search("a[href]").length > 0
end
end
if options['has_attachment']
entries = entries.send(method) do |entry|
# TODO
entry
end
end
if options['random']
entries = entries_randomly(1 - options['random'])
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
def map_entries(options = {})
return self if options = {}
options = options.with_indifferent_access
entries = self.entries
if options['images']
entries = entries.map do |entry|
title, summary, content = cleaned_content(entry)
ge = GenericEntry.create_from_entry(entry)
ge.content = Sanitize.clean(content, :elements => ['img'])
ge
end
end
if options['links']
entries = entries.map do |entry|
title, summary, content = cleaned_content(entry)
ge = GenericEntry.create_from_entry(entry)
ge.content = Sanitize.clean(content, :elements => ['a'])
ge
end
end
if options['attachments']
# TODO
end
if options['audio']
# TODO
end
if options['video']
# TODO
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
def remove_entries(options = {})
return self if options = {}
options = options.with_indifferent_access
entries = self.entries
if options['images']
end
if options['links']
end
if options['attachments']
end
if options['audio']
end
if options['video']
end
return Feedzirra::Parser::GenericParser.new(self.title, self.url, entries)
end
### Private methods
private
def cleaned_content(entry)
title = entry.title ? entry.title.downcase : ""
summary = entry.summary ? entry.summary.downcase : ""
content = entry.content ? entry.content.downcase : ""
return title, summary, content
end
end
module Parser
class GenericParser
# Not really a parser, just an object that looks like a
# Feedzirra::Parser::XX object
# TODO: what about etags, last modified, etc?
# TODO: if it's filtered, then checking for updates will be different
# I think you have to keep all the individal feeds'
# etags and last modified times around in a separate
# data structure and override the methods that check for updates
# include ::FeedZirra::FeedUtilities
# include ::FeedZirra::FeedzirraParserExtensions
PARSER_ATTRIBUTES = [:title, :url, :feed_url, :entries, :etag,
:last_modified]
include FeedUtilities
include FeedzirraParserExtensions
attr_accessor :title, :url, :feed_url, :entries, :etag, :last_modified
def initialize(title, url, entries)
self.url = url
self.title = title
# ensure this is an Array, or you can't do silly stuff like size()
self.entries = entries.to_a
end
end
class GenericEntry
INSTANCE_VARIABLES = ["@title", "@name", "@content", "@url", "@author",
"@summary", "@published", "@entry_id", "@updated", "@categories",
"@links"]
include FeedEntryUtilities
attr_accessor :title, :name, :content, :url, :author, :summary,
:published, :entry_id, :updated, :categories, :links
def self.create_from_entry(entry)
ge = GenericEntry.new
entry.instance_variables.each do |iv|
# only set attributes GenericEntries have.
if INSTANCE_VARIABLES.include?(iv)
value = entry.instance_variable_get(iv)
ge.instance_variable_set(iv, value)
end
end
end
end
end
end
# Mix in with Feedzirra parsers
# Or if you switch backends from Feedzirra you can mix in appropriately
[
Feedzirra::Parser::Atom, Feedzirra::Parser::AtomFeedBurner,
Feedzirra::Parser::ITunesRSS, Feedzirra::Parser::RSS
].each do |klass|
klass.class_eval do
include Feedzirra::FeedzirraParserExtensions
end
end |
module Flammarion
class Engraving
include Revelator
include RecognizePath
attr_accessor :on_disconnect, :on_connect, :sockets, :request, :status, :headers, :response
# Creates a new Engraving (i.e., a new display window)
# @option options [Proc] :on_connect Called when the display window is
# connected (i.e., displayed)
# @option options [Proc] :on_disconnect Called when the display windows is
# disconnected (i.e., closed)
# @option options [Boolean] :exit_on_disconnect (false) Will call +exit+
# when the widow is closed if this option is true.
# @option options [Boolean] :close_on_exit (false) Will close the window
# when the process exits if this is true. Otherwise, it will just stay
# around, but not actually be interactive.
# @raise {SetupError} if neither chrome is set up correctly and
# and Flammarion is unable to display the engraving.
def initialize(**options)
@chrome = OpenStruct.new
@sockets = []
@on_connect = options[:on_connect]
@on_disconnect = options[:on_disconnect]
@exit_on_disconnect = options.fetch(:exit_on_disconnect, false)
@processing = false
start_server
@window_id = @@server.register_window(self)
open_a_window(options) unless options[:no_window]
wait_for_a_connection unless options[:no_wait]
at_exit {close if window_open?} if options.fetch(:close_on_exit, true)
end
# Blocks the current thread until the window has been closed. All user
# interactions and callbacks will continue in other threads.
def wait_until_closed
sleep 1 until @sockets.empty?
end
# Is this Engraving displayed on the screen.
def window_open?
!@sockets.empty?
end
def disconnect(ws)
@sockets.delete ws
exit 0 if @exit_on_disconnect
@on_disconnect.call if @on_disconnect
end
def process_message(msg)
if @processing
return render(action: 'error', title: 'Processing...')
end
@processing = true
params = JSON.parse(msg).with_indifferent_access
action = params.delete(:action) || 'page'
dispatch(params)
if status == 302
params = {
url: headers['Location'].sub(/^.*:\/{2}(:\d{0,4})?/i, ''),
session: response.request.session
}.with_indifferent_access
dispatch(params)
render(action: 'page', html: response.body)
elsif headers['Content-Transfer-Encoding'] == 'binary'
filename = headers['Content-Disposition'].sub(/.*filename=/, '').gsub(/(^"|"$)/, '')
render(action: 'file', name: filename)
render(response.body)
else
render(action: action, html: response.body)
end
rescue => e
Rails.logger.error "[EXCEPTION][#{msg}]"
Rails.logger.error " [#{e.class}]\n#{e.message}\n" << e.backtrace.first(20).join("\n")
Rails.logger.error "[END]"
render(action: 'error', title: "#{e.class}: #{e.message}")
ensure
@processing = false
end
def dispatch(params)
session = params.delete(:session)
url = params.delete(:url)
uri = URI.parse(url)
query_params = Rack::Utils.parse_nested_query(uri.query)
if params.key?(:form)
params[:method] = 'post'
params[params.delete(:button)] = ''
params.merge!(Rack::Utils.parse_nested_query(params.delete(:form)))
end
if params.key?(:_method)
params[:method] = params[:_method]
end
params[:method] ||= :get
path_params = recognize_path(url, params)
unless path_params.key?(:controller)
raise ActionController::RoutingError, "No route matches [#{url}]#{params.inspect}"
end
controller_name = "#{path_params[:controller].underscore.camelize}Controller"
controller = ActiveSupport::Dependencies.constantize(controller_name)
action = path_params[:action] || 'index'
request_env = {
'rack.input' => '',
'REQUEST_METHOD' => params[:method].to_s.upcase,
'action_dispatch.request.parameters' => path_params.merge!(params).merge!(query_params),
}
request_env['rack.session'] = session if session
self.request = ActionDispatch::Request.new(request_env)
response = controller.make_response! request
self.status, self.headers, body = controller.dispatch(action, request, response)
self.response = body.instance_variable_get(:@response)
end
def start_server
@@server ||= Server.new
end
def server
@@server
end
def render(body)
if @sockets.empty?
open_a_window
wait_for_a_connection
end
if body.is_a? Hash
body = body.to_json
else
binary = true
end
@sockets.each do |ws|
ws.send_data(body, binary)
end
nil
end
end
end
blocking is useless (its a server)
module Flammarion
class Engraving
include Revelator
include RecognizePath
attr_accessor :on_disconnect, :on_connect, :sockets, :request, :status, :headers, :response
# Creates a new Engraving (i.e., a new display window)
# @option options [Proc] :on_connect Called when the display window is
# connected (i.e., displayed)
# @option options [Proc] :on_disconnect Called when the display windows is
# disconnected (i.e., closed)
# @option options [Boolean] :exit_on_disconnect (false) Will call +exit+
# when the widow is closed if this option is true.
# @option options [Boolean] :close_on_exit (false) Will close the window
# when the process exits if this is true. Otherwise, it will just stay
# around, but not actually be interactive.
# @raise {SetupError} if neither chrome is set up correctly and
# and Flammarion is unable to display the engraving.
def initialize(**options)
@chrome = OpenStruct.new
@sockets = []
@on_connect = options[:on_connect]
@on_disconnect = options[:on_disconnect]
@exit_on_disconnect = options.fetch(:exit_on_disconnect, false)
start_server
@window_id = @@server.register_window(self)
open_a_window(options) unless options[:no_window]
wait_for_a_connection unless options[:no_wait]
at_exit {close if window_open?} if options.fetch(:close_on_exit, true)
end
# Blocks the current thread until the window has been closed. All user
# interactions and callbacks will continue in other threads.
def wait_until_closed
sleep 1 until @sockets.empty?
end
# Is this Engraving displayed on the screen.
def window_open?
!@sockets.empty?
end
def disconnect(ws)
@sockets.delete ws
exit 0 if @exit_on_disconnect
@on_disconnect.call if @on_disconnect
end
def process_message(msg)
params = JSON.parse(msg).with_indifferent_access
action = params.delete(:action) || 'page'
dispatch(params)
if status == 302
params = {
url: headers['Location'].sub(/^.*:\/{2}(:\d{0,4})?/i, ''),
session: response.request.session
}.with_indifferent_access
dispatch(params)
render(action: 'page', html: response.body)
elsif headers['Content-Transfer-Encoding'] == 'binary'
filename = headers['Content-Disposition'].sub(/.*filename=/, '').gsub(/(^"|"$)/, '')
render(action: 'file', name: filename)
render(response.body)
else
render(action: action, html: response.body)
end
rescue => e
Rails.logger.error "[EXCEPTION][#{msg}]"
Rails.logger.error " [#{e.class}]\n#{e.message}\n" << e.backtrace.first(20).join("\n")
Rails.logger.error "[END]"
render(action: 'error', title: "#{e.class}: #{e.message}")
end
def dispatch(params)
session = params.delete(:session)
url = params.delete(:url)
uri = URI.parse(url)
query_params = Rack::Utils.parse_nested_query(uri.query)
if params.key?(:form)
params[:method] = 'post'
params[params.delete(:button)] = ''
params.merge!(Rack::Utils.parse_nested_query(params.delete(:form)))
end
if params.key?(:_method)
params[:method] = params[:_method]
end
params[:method] ||= :get
path_params = recognize_path(url, params)
unless path_params.key?(:controller)
raise ActionController::RoutingError, "No route matches [#{url}]#{params.inspect}"
end
controller_name = "#{path_params[:controller].underscore.camelize}Controller"
controller = ActiveSupport::Dependencies.constantize(controller_name)
action = path_params[:action] || 'index'
request_env = {
'rack.input' => '',
'REQUEST_METHOD' => params[:method].to_s.upcase,
'action_dispatch.request.parameters' => path_params.merge!(params).merge!(query_params),
}
request_env['rack.session'] = session if session
self.request = ActionDispatch::Request.new(request_env)
response = controller.make_response! request
self.status, self.headers, body = controller.dispatch(action, request, response)
self.response = body.instance_variable_get(:@response)
end
def start_server
@@server ||= Server.new
end
def server
@@server
end
def render(body)
if @sockets.empty?
open_a_window
wait_for_a_connection
end
if body.is_a? Hash
body = body.to_json
else
binary = true
end
@sockets.each do |ws|
ws.send_data(body, binary)
end
nil
end
end
end
|
#!/usr/bin/env ruby
require 'em-resque/worker'
require 'flapjack/daemonizing'
require 'flapjack/notification/email'
require 'flapjack/notification/sms'
require 'flapjack/notification/jabber'
require 'flapjack/executive'
require 'flapjack/web'
module Flapjack
class Coordinator
include Flapjack::Daemonizable
def initialize(config = {})
@config = config
@pikelets = []
end
def start(options = {})
# FIXME raise error if config not set, or empty
if options[:daemonize]
daemonize
else
setup
setup_signals
end
end
# clean shutdown
def stop
@pikelets.each do |pik|
case pik
when Flapjack::Executive
pik.stop
Fiber.new {
pik.add_shutdown_event
}.resume
when EM::Resque::Worker
# resque is polling, so won't need a shutdown object
pik.shutdown
when Thin::Server
pik.stop
end
end
# # TODO call EM.stop after polling to check whether all of the
# # above have finished
# EM.stop
end
# not-so-clean shutdown
def stop!
stop
# FIXME wrap the above in a timeout?
end
def after_daemonize
# FIXME ideally we'd setup_signals after setup, but something in web is blocking
# when we're running daemonized :/
setup_signals
setup
end
def setup_signals
trap('INT') { stop! }
trap('TERM') { stop }
unless RUBY_PLATFORM =~ /mswin/
trap('QUIT') { stop }
# trap('HUP') { restart }
# trap('USR1') { reopen_log }
end
end
private
def setup
# TODO if we want to run the same pikelet with different settings,
# we could require each setting to include a type, and treat the
# key as the name of the config -- for now, YAGNI.
# TODO store these in the classes themselves, register pikelets here?
pikelet_types = {
'executive' => Flapjack::Executive,
'web' => Flapjack::Web,
'email_notifier' => Flapjack::Notification::Email,
'sms_notifier' => Flapjack::Notification::Sms
}
EM.synchrony do
unless (['email_notifier', 'sms_notifier'] & @config.keys).empty?
# make Resque a slightly nicer citizen
require 'flapjack/resque_patches'
# set up connection pooling, stop resque errors
EM::Resque.initialize_redis(::Redis.new(@config['redis']))
end
def fiberise_instances(instance_num, &block)
(1..[1, instance_num || 1].max).each do |n|
Fiber.new {
block.yield
}.resume
end
end
@config.keys.each do |pikelet_type|
next unless pikelet_types.has_key?(pikelet_type)
pikelet_cfg = @config[pikelet_type]
case pikelet_type
when 'executive'
fiberise_instances(pikelet_cfg['instances'].to_i) {
flapjack_exec = Flapjack::Executive.new(pikelet_cfg.merge(:redis => {:driver => 'synchrony'}))
@pikelets << flapjack_exec
flapjack_exec.main
}
when 'email_notifier', 'sms_notifier'
pikelet = pikelet_types[pikelet_type]
# TODO error if pikelet_cfg['queue'].nil?
# # Deferring this: Resque's not playing well with evented code
# if 'email_notifier'.eql?(pikelet_type)
# pikelet.class_variable_set('@@actionmailer_config', actionmailer_config)
# end
fiberise_instances(pikelet_cfg['instances']) {
flapjack_rsq = EM::Resque::Worker.new(pikelet_cfg['queue'])
# # Use these to debug the resque workers
# flapjack_rsq.verbose = true
# flapjack_rsq.very_verbose = true
@pikelets << flapjack_rsq
flapjack_rsq.work(0.1)
}
when 'jabber_gateway'
fiberise_instances(pikelet_cfg['instances']) {
flapjack_jabbers = Flapjack::Notification::Jabber.new(pikelet_cfg)
flapjack_jabbers.main
}
when 'web'
port = nil
if pikelet_cfg['thin_config'] && pikelet_cfg['thin_config']['port']
port = pikelet_cfg['thin_config']['port'].to_i
end
port = 3000 if port.nil? || port <= 0 || port > 65535
thin = Thin::Server.new('0.0.0.0', port, Flapjack::Web, :signals => false)
@pikelets << thin
thin.start
end
end
end
end
end
end
fix signal handling, whether daemonized or not
#!/usr/bin/env ruby
require 'em-resque/worker'
require 'flapjack/daemonizing'
require 'flapjack/notification/email'
require 'flapjack/notification/sms'
require 'flapjack/notification/jabber'
require 'flapjack/executive'
require 'flapjack/web'
module Flapjack
class Coordinator
include Flapjack::Daemonizable
def initialize(config = {})
@config = config
@pikelets = []
end
def start(options = {})
# FIXME raise error if config not set, or empty
if options[:daemonize]
daemonize
else
setup
end
end
# clean shutdown
def stop
@pikelets.each do |pik|
case pik
when Flapjack::Executive
pik.stop
Fiber.new {
pik.add_shutdown_event
}.resume
when EM::Resque::Worker
# resque is polling, so won't need a shutdown object
pik.shutdown
when Thin::Server
pik.stop
end
end
# # TODO call EM.stop after polling to check whether all of the
# # above have finished
# EM.stop
end
# not-so-clean shutdown
def stop!
stop
# FIXME wrap the above in a timeout?
end
def after_daemonize
setup
end
private
def setup
# TODO if we want to run the same pikelet with different settings,
# we could require each setting to include a type, and treat the
# key as the name of the config -- for now, YAGNI.
# TODO store these in the classes themselves, register pikelets here?
pikelet_types = {
'executive' => Flapjack::Executive,
'web' => Flapjack::Web,
'email_notifier' => Flapjack::Notification::Email,
'sms_notifier' => Flapjack::Notification::Sms
}
EM.synchrony do
unless (['email_notifier', 'sms_notifier'] & @config.keys).empty?
# make Resque a slightly nicer citizen
require 'flapjack/resque_patches'
# set up connection pooling, stop resque errors
EM::Resque.initialize_redis(::Redis.new(@config['redis']))
end
def fiberise_instances(instance_num, &block)
(1..[1, instance_num || 1].max).each do |n|
Fiber.new {
block.yield
}.resume
end
end
@config.keys.each do |pikelet_type|
next unless pikelet_types.has_key?(pikelet_type)
pikelet_cfg = @config[pikelet_type]
case pikelet_type
when 'executive'
fiberise_instances(pikelet_cfg['instances'].to_i) {
flapjack_exec = Flapjack::Executive.new(pikelet_cfg.merge(:redis => {:driver => 'synchrony'}))
@pikelets << flapjack_exec
flapjack_exec.main
}
when 'email_notifier', 'sms_notifier'
pikelet = pikelet_types[pikelet_type]
# TODO error if pikelet_cfg['queue'].nil?
# # Deferring this: Resque's not playing well with evented code
# if 'email_notifier'.eql?(pikelet_type)
# pikelet.class_variable_set('@@actionmailer_config', actionmailer_config)
# end
fiberise_instances(pikelet_cfg['instances']) {
flapjack_rsq = EM::Resque::Worker.new(pikelet_cfg['queue'])
# # Use these to debug the resque workers
# flapjack_rsq.verbose = true
# flapjack_rsq.very_verbose = true
@pikelets << flapjack_rsq
flapjack_rsq.work(0.1)
}
when 'jabber_gateway'
fiberise_instances(pikelet_cfg['instances']) {
flapjack_jabbers = Flapjack::Notification::Jabber.new(pikelet_cfg)
flapjack_jabbers.main
}
when 'web'
port = nil
if pikelet_cfg['thin_config'] && pikelet_cfg['thin_config']['port']
port = pikelet_cfg['thin_config']['port'].to_i
end
port = 3000 if port.nil? || port <= 0 || port > 65535
thin = Thin::Server.new('0.0.0.0', port, Flapjack::Web, :signals => false)
@pikelets << thin
thin.start
end
end
setup_signals
end
end
def setup_signals
trap('INT') { stop! }
trap('TERM') { stop }
unless RUBY_PLATFORM =~ /mswin/
trap('QUIT') { stop }
# trap('HUP') { restart }
# trap('USR1') { reopen_log }
end
end
end
end
|
require 'minitest_helper'
class TestLknovel < MiniTest::Unit::TestCase
def test_that_it_has_a_version_number
refute_nil ::Lknovel::VERSION
end
def test_it_does_something_useful
assert false
end
end
Remove test from skel
require 'minitest_helper'
|
require 'flattr/thing'
module Flattr
class Client
module Things
def thing(id)
thing = get("/rest/v2/things/#{id}")
Flattr::Thing.new(thing)
end
def thing_new(url, opts = {})
response = post("/rest/v2/things", opts.merge(:url => url))
thing = get("/rest/v2/things/#{response[:id]}")
Flattr::Thing.new(thing)
end
def thing_update(id, opts = {})
patch("/rest/v2/things/#{id}", opts)
thing = get("/rest/v2/things/#{id}")
Flattr::Thing.new(thing)
end
def thing_delete(id)
thing = delete("/rest/v2/things/#{id}")
puts thing.inspect
true
end
def search(params = {})
result = get("/rest/v2/things/search", params)
Flattr::Search.new(result)
end
def lookup(url)
thing = get("/rest/v2/things/lookup/", {:url => url})
Flattr::Thing.new(thing)
end
end
end
end
Fix delete and lookup
require 'flattr/thing'
module Flattr
class Client
module Things
def thing(id)
thing = get("/rest/v2/things/#{id}")
Flattr::Thing.new(thing)
end
def thing_new(url, opts = {})
response = post("/rest/v2/things", opts.merge(:url => url))
thing = get("/rest/v2/things/#{response[:id]}")
Flattr::Thing.new(thing)
end
def thing_update(id, opts = {})
patch("/rest/v2/things/#{id}", opts)
thing = get("/rest/v2/things/#{id}")
Flattr::Thing.new(thing)
end
def thing_delete(id)
thing = delete("/rest/v2/things/#{id}")
if thing.nil? || thing == ""
return true
else
return false
end
end
def thing_search(params = {})
result = get("/rest/v2/things/search", params)
Flattr::Search.new(result)
end
def thing_lookup(url)
lookup = get("/rest/v2/things/lookup", {:url => url})
if lookup["location"]
thing = get(lookup['location'])
Flattr::Thing.new(thing)
else
nil
end
end
end
end
end
|
require 'pp'
require 'stringio'
require 'erb'
Infinity = 1/0.0 unless defined?(Infinity)
NaN = 0/0.0 unless defined?(NaN)
module Kernel
# Compute the difference (delta) between two values.
#
# When a block is given the block will be applied to both arguments.
# Using a block in this way allows computation against a specific field
# in a data set of hashes or objects.
#
# @yield iterates over each element in the data set
# @yieldparam item each element in the data set
#
# @param [Object] v1 the first value
# @param [Object] v2 the second value
#
# @return [Float] positive value representing the difference
# between the two parameters
def delta(v1, v2)
if block_given?
v1 = yield(v1)
v2 = yield(v2)
end
return (v1 - v2).abs
end
module_function :delta
# Perform an operation numerous times, passing the value of the
# previous iteration, and collecting the results into an array.
#
# @yield iterates over each element in the data set
# @yieldparam previous the initial value (or nil) for the first
# iteration then the value of the previous iteration for all
# subsequent iterations
#
# @param [Integer] count the number of times to perform the operation
# @param [Object] initial the initial value to pass to the first iteration
#
# @return [Array] the results of the iterations collected into an array
def repeatedly(count, initial = nil)
return [] if (count = count.to_i) == 0
return count.times.collect{ nil } unless block_given?
return count.times.collect do
initial = yield(initial)
end
end
module_function :repeatedly
# Try an operation. If it fails (raises an exception), wait a second
# and try again. Try no more than the given number of times.
#
# @yield Tries the given block operation
#
# @param [Integer] tries The maximum number of times to attempt the operation.
# @param [Array] args Optional block arguments
#
# @return [Boolean] true if the operation succeeds on any attempt,
# false if none of the attempts are successful
def retro(tries, *args)
tries = tries.to_i
return false if tries == 0 || ! block_given?
yield(*args)
return true
rescue Exception
sleep(1)
if (tries = tries - 1) > 0
retry
else
return false
end
end
module_function :retro
# Sandbox the given operation at a high $SAFE level.
#
# @param args [Array] zero or more arguments to pass to the block
#
# @return [Object] the result of the block operation
def safe(*args)
raise ArgumentError.new('no block given') unless block_given?
result = nil
t = Thread.new do
$SAFE = 3
result = yield(*args)
end
t.join
return result
end
module_function :safe
# Open a file, read it, close the file, and return its contents.
#
# @param file [String] path to and name of the file to open
#
# @return [String] file contents
#
# @see slurpee
def slurp(file)
File.open(file, 'rb') {|f| f.read }
end
module_function :slurp
# Open a file, read it, close the file, run the contents through the
# ERB parser, and return updated contents.
#
# @param file [String] path to and name of the file to open
# @param safe_level [Integer] when not nil, ERB will $SAFE set to this
#
# @return [String] file contents
#
# @see slurpee
def slurpee(file, safe_level = nil)
ERB.new(slurp(file), safe_level).result
end
module_function :slurpee
# Run the given block and time how long it takes in seconds. All arguments
# will be passed to the block. The function will return two values. The
# first value will be the duration of the timer in seconds. The second
# return value will be the result of the block.
#
# @param args [Array] zero or more arguments to pass to the block
#
# @return [Integer, Object] the duration of the operation in seconds and
# the result of the block operation
def timer(*args)
return 0,nil unless block_given?
t1 = Time.now
result = yield(*args)
t2 = Time.now
return (t2 - t1), result
end
module_function :timer
#############################################################################
# @private
def repl? # :nodoc:
return ($0 == 'irb' || $0 == 'pry' || $0 == 'script/rails' || !!($0 =~ /bin\/bundle$/))
end
module_function :repl?
# @private
def timestamp # :nodoc:
return Time.now.getutc.to_i
end
# @private
def strftimer(seconds) # :nodoc:
Time.at(seconds).gmtime.strftime('%R:%S.%L')
end
module_function :strftimer
# @private
# @see http://rhaseventh.blogspot.com/2008/07/ruby-and-rails-how-to-get-pp-pretty.html
def pp_s(*objs) # :nodoc:
s = StringIO.new
objs.each {|obj|
PP.pp(obj, s)
}
s.rewind
s.read
end
module_function :pp_s
end
Added utilities for counting objects in the ObjectSpace.
require 'pp'
require 'stringio'
require 'erb'
Infinity = 1/0.0 unless defined?(Infinity)
NaN = 0/0.0 unless defined?(NaN)
module Kernel
# Compute the difference (delta) between two values.
#
# When a block is given the block will be applied to both arguments.
# Using a block in this way allows computation against a specific field
# in a data set of hashes or objects.
#
# @yield iterates over each element in the data set
# @yieldparam item each element in the data set
#
# @param [Object] v1 the first value
# @param [Object] v2 the second value
#
# @return [Float] positive value representing the difference
# between the two parameters
def delta(v1, v2)
if block_given?
v1 = yield(v1)
v2 = yield(v2)
end
return (v1 - v2).abs
end
module_function :delta
# Perform an operation numerous times, passing the value of the
# previous iteration, and collecting the results into an array.
#
# @yield iterates over each element in the data set
# @yieldparam previous the initial value (or nil) for the first
# iteration then the value of the previous iteration for all
# subsequent iterations
#
# @param [Integer] count the number of times to perform the operation
# @param [Object] initial the initial value to pass to the first iteration
#
# @return [Array] the results of the iterations collected into an array
def repeatedly(count, initial = nil)
return [] if (count = count.to_i) == 0
return count.times.collect{ nil } unless block_given?
return count.times.collect do
initial = yield(initial)
end
end
module_function :repeatedly
# Try an operation. If it fails (raises an exception), wait a second
# and try again. Try no more than the given number of times.
#
# @yield Tries the given block operation
#
# @param [Integer] tries The maximum number of times to attempt the operation.
# @param [Array] args Optional block arguments
#
# @return [Boolean] true if the operation succeeds on any attempt,
# false if none of the attempts are successful
def retro(tries, *args)
tries = tries.to_i
return false if tries == 0 || ! block_given?
yield(*args)
return true
rescue Exception
sleep(1)
if (tries = tries - 1) > 0
retry
else
return false
end
end
module_function :retro
# Sandbox the given operation at a high $SAFE level.
#
# @param args [Array] zero or more arguments to pass to the block
#
# @return [Object] the result of the block operation
def safe(*args)
raise ArgumentError.new('no block given') unless block_given?
result = nil
t = Thread.new do
$SAFE = 3
result = yield(*args)
end
t.join
return result
end
module_function :safe
# Open a file, read it, close the file, and return its contents.
#
# @param file [String] path to and name of the file to open
#
# @return [String] file contents
#
# @see slurpee
def slurp(file)
File.open(file, 'rb') {|f| f.read }
end
module_function :slurp
# Open a file, read it, close the file, run the contents through the
# ERB parser, and return updated contents.
#
# @param file [String] path to and name of the file to open
# @param safe_level [Integer] when not nil, ERB will $SAFE set to this
#
# @return [String] file contents
#
# @see slurpee
def slurpee(file, safe_level = nil)
ERB.new(slurp(file), safe_level).result
end
module_function :slurpee
# Run the given block and time how long it takes in seconds. All arguments
# will be passed to the block. The function will return two values. The
# first value will be the duration of the timer in seconds. The second
# return value will be the result of the block.
#
# @param args [Array] zero or more arguments to pass to the block
#
# @return [Integer, Object] the duration of the operation in seconds and
# the result of the block operation
def timer(*args)
return 0,nil unless block_given?
t1 = Time.now
result = yield(*args)
t2 = Time.now
return (t2 - t1), result
end
module_function :timer
#############################################################################
# @private
# @see http://cirw.in/blog/find-references
def object_counts # :nodoc:
counts = Hash.new{ 0 }
ObjectSpace.each_object do |obj|
counts[obj.class] += 1
end
return counts
end
module_function :object_counts
# @private
# @see http://rhaseventh.blogspot.com/2008/07/ruby-and-rails-how-to-get-pp-pretty.html
def pp_s(*objs) # :nodoc:
s = StringIO.new
objs.each {|obj|
PP.pp(obj, s)
}
s.rewind
s.read
end
module_function :pp_s
# @private
def repl? # :nodoc:
return ($0 == 'irb' || $0 == 'pry' || $0 == 'script/rails' || !!($0 =~ /bin\/bundle$/))
end
module_function :repl?
# @private
def strftimer(seconds) # :nodoc:
Time.at(seconds).gmtime.strftime('%R:%S.%L')
end
module_function :strftimer
# @private
def timestamp # :nodoc:
return Time.now.getutc.to_i
end
def write_object_counts(name = 'ruby')
file = "#{name}_#{Time.now.to_i}.txt"
File.open(file, 'w') {|f| f.write(pp_s(object_counts)) }
end
module_function :write_object_counts
end
|
module Gem::Search
module Rendering
# NAME', 'DL(ver)', 'DL(all)', 'HOMEPAGE'
DEFAULT_RULED_LINE_SIZE = [50, 8, 9, 60]
def self.included(base)
base.extend(self)
end
def render(gems, opt_detail)
@opt_detail = opt_detail
ruled_line_size(gems)
render_to_header
render_to_body(gems)
end
private
def ruled_line_size(gems)
@ruled_line_size = DEFAULT_RULED_LINE_SIZE.dup
max_name_size = gems.map { |gem| "#{gem['name'] } (#{gem['version']})".size }.max
@ruled_line_size[0] = max_name_size if max_name_size > @ruled_line_size[0]
end
def render_to_header
f = @ruled_line_size
fmt = "%-#{f[0]}s %#{f[1]}s %#{f[2]}s"
titles = ['NAME', 'DL(ver)', 'DL(all)']
hyphens = ['-'*f[0], '-'*f[1], '-'*f[2]]
if @opt_detail
fmt << " %-#{f[3]}s"
titles << 'HOMEPAGE'
hyphens << '-'*f[3]
end
puts fmt % titles
puts fmt % hyphens
end
def render_to_body(gems)
f = @ruled_line_size
fmt = "%-#{f[0]}s %#{f[1]}d %#{f[2]}d"
fmt << " %-#{f[3]}s" if @opt_detail
gems.each do |gem|
columns = [
"#{gem['name']} (#{gem['version']})",
gem['version_downloads'],
gem['downloads']
]
columns << gem['homepage_uri'] if @opt_detail
puts fmt % columns
end
end
end
end
Remove an whitespace
module Gem::Search
module Rendering
# NAME', 'DL(ver)', 'DL(all)', 'HOMEPAGE'
DEFAULT_RULED_LINE_SIZE = [50, 8, 9, 60]
def self.included(base)
base.extend(self)
end
def render(gems, opt_detail)
@opt_detail = opt_detail
ruled_line_size(gems)
render_to_header
render_to_body(gems)
end
private
def ruled_line_size(gems)
@ruled_line_size = DEFAULT_RULED_LINE_SIZE.dup
max_name_size = gems.map { |gem| "#{gem['name']} (#{gem['version']})".size }.max
@ruled_line_size[0] = max_name_size if max_name_size > @ruled_line_size[0]
end
def render_to_header
f = @ruled_line_size
fmt = "%-#{f[0]}s %#{f[1]}s %#{f[2]}s"
titles = ['NAME', 'DL(ver)', 'DL(all)']
hyphens = ['-'*f[0], '-'*f[1], '-'*f[2]]
if @opt_detail
fmt << " %-#{f[3]}s"
titles << 'HOMEPAGE'
hyphens << '-'*f[3]
end
puts fmt % titles
puts fmt % hyphens
end
def render_to_body(gems)
f = @ruled_line_size
fmt = "%-#{f[0]}s %#{f[1]}d %#{f[2]}d"
fmt << " %-#{f[3]}s" if @opt_detail
gems.each do |gem|
columns = [
"#{gem['name']} (#{gem['version']})",
gem['version_downloads'],
gem['downloads']
]
columns << gem['homepage_uri'] if @opt_detail
puts fmt % columns
end
end
end
end
|
# lib/gemwarrior/evaluator.rb
# Evaluates prompt input
require_relative 'arena'
require_relative 'game_assets'
require_relative 'game_options'
module Gemwarrior
class Evaluator
# CONSTANTS
PROGRAM_NAME = 'Gem Warrior'
QUIT_MESSAGE = 'Thanks for playing the game. Until next time...'.colorize(:yellow)
RESUME_MESSAGE = 'Back to adventuring!'.colorize(:green)
GO_PARAMS = 'Options: north, east, south, west'
CHANGE_PARAMS = 'Options: name'
DEBUG_LIST_PARAMS = 'Options: players, creatures, items, locations, monsters, weapons'
DEBUG_STAT_PARAMS = 'Options: hp_cur, atk_lo, atk_hi, experience, rox, strength, dexterity, defense, inventory'
ERROR_COMMAND_INVALID = 'That is not something the game yet understands.'
ERROR_LOOK_AT_PARAM_MISSING = 'You cannot just "look at". You gotta choose something to look at.'
ERROR_TALK_PARAM_INVALID = 'Are you talking to yourself? That person is not here.'
ERROR_TALK_PARAM_UNTALKABLE = 'That cannnot be conversed with.'
ERROR_TALK_TO_PARAM_MISSING = 'You cannot just "talk to". You gotta choose someone to talk to.'
ERROR_GO_PARAM_MISSING = 'Just wander aimlessly? A direction would be nice.'
ERROR_GO_PARAM_INVALID = 'Something tells you that is not a way to go.'
ERROR_DIRECTION_PARAM_INVALID = 'You cannot go to that place.'
ERROR_ATTACK_PARAM_MISSING = 'You cannot just "attack". You gotta choose something to attack.'
ERROR_ATTACK_PARAM_INVALID = 'That monster does not exist here or can\'t be attacked.'
ERROR_TAKE_PARAM_MISSING = 'You cannot just "take". You gotta choose something to take.'
ERROR_USE_PARAM_MISSING = 'You cannot just "use". You gotta choose something to use.'
ERROR_USE_PARAM_INVALID = 'You cannot use that, as it does not exist here or in your inventory.'
ERROR_USE_PARAM_UNUSEABLE = 'That is not useable.'
ERROR_DROP_PARAM_MISSING = 'You cannot just "drop". You gotta choose something to drop.'
ERROR_EQUIP_PARAM_MISSING = 'You cannot just "equip". You gotta choose something to equip.'
ERROR_UNEQUIP_PARAM_MISSING = 'You cannot just "unequip". You gotta choose something to unequip.'
ERROR_CHANGE_PARAM_MISSING = 'You cannot just "change". You gotta choose something to change.'
ERROR_CHANGE_PARAM_INVALID = 'You cannot change that...yet.'
ERROR_LIST_PARAM_MISSING = 'You cannot just "list". You gotta choose something to list.'
ERROR_LIST_PARAM_INVALID = 'You cannot list that...yet.'
ERROR_DEBUG_STAT_PARAM_MISSING = 'You cannot just "change stats". You gotta choose a stat to change.'
ERROR_DEBUG_STAT_PARAM_INVALID = 'You cannot change that stat...yet.'
ERROR_DEBUG_STAT_INV_PARAM_INVALID = 'You cannot add that to your inventory...yet.'
ERROR_DEBUG_GLOBAL_VAR_INVALID = 'That global variable does not exist.'
ERROR_DEBUG_TELEPORT_PARAMS_MISSING = 'You cannot just "teleport". You gotta specify an x AND y coordinate, at least.'
ERROR_DEBUG_TELEPORT_PARAMS_NEEDED = 'You cannot just "teleport" to an x coordinate without a y coordinate.'
ERROR_DEBUG_TELEPORT_PARAMS_INVALID = 'You cannot teleport there...yet.'
attr_accessor :world,
:commands,
:aliases,
:extras,
:cmd_descriptions,
:devcommands,
:devaliases,
:devextras,
:devcmd_descriptions
def initialize(world)
self.world = world
self.devcommands = %w(god beast constants list vars map stat global teleport spawn levelbump restfight)
self.devaliases = %w(gd bs cn ls vs m st gl tp sp lb rf)
self.devextras = %w()
self.devcmd_descriptions = [
'Toggle god mode (i.e. invincible)',
'Toggle beast mode (i.e. super strength)',
'List all GameAssets',
'List all instances of a specific entity type',
'List all the variables in the world',
'Show a map of the world',
'Change player stat',
'Change world global variable',
'Teleport to coordinates (5 0 0) or name (\'Home\')',
'Spawn random monster',
'Bump your character up *n* levels',
'Rest, but ensure battle for testing'
]
self.commands = %w(character look rest take talk inventory use drop equip unequip go north east south west attack change version checkupdate help quit quit!)
self.aliases = %w(c l r t tk i u d eq ue g n e s w a ch v cu h q qq)
self.extras = %w(exit exit! x xx fight f ? ?? ???)
self.cmd_descriptions = [
'Display character information',
'Look around your current location',
'Take a load off and regain HP',
'Take item',
'Talk to person',
'Look in your inventory',
'Use item (in inventory or environment)',
'Drop item',
'Equip item',
'Unequip item',
'Go in a direction',
'Go north (shortcut)',
'Go east (shortcut)',
'Go south (shortcut)',
'Go west (shortcut)',
'Attack a monster (also fight)',
'Change attribute',
'Display game version',
'Check for newer game releases',
'This help menu (also ?)',
'Quit w/ confirmation (also exit/x)',
'Quit w/o confirmation (also exit!/xx)'
]
end
def parse(input)
case input
# Ctrl-D or empty command
when nil, ''
return
# real command
else
return ERROR_COMMAND_INVALID.colorize(:red) unless input_valid?(input)
end
tokens = input.split
command = tokens.first.downcase
param1 = tokens[1]
param2 = tokens[2]
param3 = tokens[3]
# helpful
player_cur_location = world.location_by_coords(world.player.cur_coords)
# dev commands
if GameOptions.data['debug_mode']
case command
when 'god', 'gd'
GameOptions.data['god_mode'] = !GameOptions.data['god_mode']
return "God mode set to #{GameOptions.data['god_mode']}"
when 'beast', 'bs'
GameOptions.data['beast_mode'] = !GameOptions.data['beast_mode']
return "Beast mode set to #{GameOptions.data['beast_mode']}"
when 'constants', 'cn'
puts 'GameCreatures'.colorize(:yellow)
puts GameCreatures.data
STDIN.getc
puts 'GameMonsters'.colorize(:yellow)
puts GameMonsters.data
STDIN.getc
puts 'GamePeople'.colorize(:yellow)
puts GamePeople.data
STDIN.getc
puts 'GameItems'.colorize(:yellow)
puts GameItems.data
STDIN.getc
puts 'GameArmor'.colorize(:yellow)
puts GameArmor.data
STDIN.getc
puts 'GameWeapons'.colorize(:yellow)
puts GameWeapons.data
when 'vars', 'vs'
if param1
world.print_vars(param1)
else
world.print_vars
end
when 'list', 'ls'
if param1.nil?
puts ERROR_LIST_PARAM_MISSING
return DEBUG_LIST_PARAMS
else
return world.list(param1, param2)
end
when 'map', 'm'
world.print_map(param1)
when 'stat', 'st'
if param1.nil?
puts ERROR_DEBUG_STAT_PARAM_MISSING
return DEBUG_STAT_PARAMS
else
case param1
when 'hp_cur', 'hp'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 > 0
world.player.hp_cur = param2
end
end
end
when 'atk_lo'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.atk_lo = param2
end
end
end
when 'atk_hi'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.atk_hi = param2
end
end
end
when 'strength', 'str', 'st'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.atk_lo = param2
world.player.atk_hi = param2
end
end
end
when 'dexterity', 'dex'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.dexterity = param2
end
end
end
when 'defense', 'def'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.defense = param2
end
end
end
when 'rox', 'r', '$'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.rox = param2
end
end
end
when 'experience', 'xp'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.xp = param2
end
end
end
when 'inventory', 'inv'
unless param2.nil?
begin
item_const_name = Gemwarrior.const_get(Formatting.upstyle(param2, no_space: true))
item = item_const_name.new
world.player.inventory.items.push(item)
return "#{item.name} added to player inventory."
rescue
return ERROR_DEBUG_STAT_INV_PARAM_INVALID
end
end
else
return ERROR_DEBUG_STAT_PARAM_INVALID
end
end
when 'global', 'gl'
if param1.nil?
return world.instance_variables.join(', ')
elsif world.instance_variable_get("@#{param1}").nil?
return ERROR_DEBUG_GLOBAL_VAR_INVALID
elsif param2.nil?
return world.instance_variable_get("@#{param1}").to_s
else
val = false
val = param2.eql?('true') ? true : val
world.instance_variable_set("@#{param1}", val)
return "Instance variable #{param1} has been set to #{val}."
end
when 'spawn', 'sp'
player_cur_location = world.location_by_coords(world.player.cur_coords)
player_cur_location.populate_monsters(GameMonsters.data, spawn: true)
return world.describe(player_cur_location)
when 'teleport', 'tp'
if param1.nil?
return ERROR_DEBUG_TELEPORT_PARAMS_MISSING
else
if (param1.to_i.to_s == param1)
# we got at least an x coordinate
if (param2.to_i.to_s == param2)
# we got a y coordinate, too
x_coord = param1.to_i
y_coord = param2.to_i
# grab the z coordinate, if present, otherwise default to current level
z_coord = param3.to_i.to_s == param3 ? param3.to_i : world.player.cur_coords[:z]
# check to make sure new location exists
if world.location_by_coords(x: x_coord, y: y_coord, z: z_coord)
world.player.cur_coords = { x: x_coord, y: y_coord, z: z_coord }
else
return ERROR_DEBUG_TELEPORT_PARAMS_INVALID
end
else
# we only got an x coordinate
return ERROR_DEBUG_TELEPORT_PARAMS_NEEDED
end
else
# we got a place name instead, potentially
place_to_match = tokens[1..tokens.length].join(' ').downcase
locations = []
world.locations.each do |l|
locations << l.name.downcase
end
if locations.include?(place_to_match)
world.player.cur_coords = world.location_coords_by_name(place_to_match)
else
return ERROR_DEBUG_TELEPORT_PARAMS_INVALID
end
end
# stats
world.player.movements_made += 1
Animation.run(phrase: '** TELEPORT! **', speed: :insane)
player_cur_location = world.location_by_coords(world.player.cur_coords)
return world.describe(player_cur_location)
end
when 'levelbump', 'lb'
new_level = param1.nil? ? 1 : param1.to_i
world.player.update_stats(reason: :level_bump, value: new_level)
when 'restfight', 'rf'
result = world.player.rest(world, 0, true)
if result.eql?('death')
player_death_resurrection
end
end
end
# normal commands
case command
when 'character', 'c'
# bypass puts so it prints out with newlines properly
print world.player.check_self
when 'inventory', 'i'
if param1
world.player.inventory.describe_item(param1)
else
world.player.list_inventory
end
when 'look', 'l'
if param1
# convert 'look at' to 'look'
if param1.eql?('at')
if param2
param1 = param2
else
return ERROR_LOOK_AT_PARAM_MISSING
end
end
world.describe_entity(player_cur_location, param1)
else
world.describe(player_cur_location)
end
when 'rest', 'r'
tent_uses = 0
player_inventory = world.player.inventory
if player_inventory.contains_item?('tent')
player_inventory.items.each do |i|
if i.name.eql?('tent')
if i.number_of_uses > 0
result = i.use(world)
tent_uses = i.number_of_uses
i.number_of_uses -= 1
puts ">> tent can be used when resting #{i.number_of_uses} more time(s)."
end
end
end
elsif player_cur_location.contains_item?('tent')
player_cur_location.items.each do |i|
if i.name.eql?('tent')
if i.number_of_uses > 0
result = i.use(world)
tent_uses = i.number_of_uses
i.number_of_uses -= 1
puts ">> tent can be used when resting #{i.number_of_uses} more time(s)."
end
end
end
end
result = world.player.rest(world, tent_uses)
if result.eql?('death')
player_death_resurrection
else
result
end
when 'take', 't'
if param1.nil?
ERROR_TAKE_PARAM_MISSING
else
world.player.inventory.add_item(param1, player_cur_location, world.player)
end
when 'talk', 'tk'
if param1.nil?
return ERROR_TALK_TO_PARAM_MISSING
elsif param1.eql?('to')
if param2
param1 = param2
else
return ERROR_TALK_TO_PARAM_MISSING
end
end
talkable_name = param1
player_inventory = world.player.inventory
if player_inventory.contains_item?(talkable_name)
player_inventory.items.each do |person|
if person.name.eql?(talkable_name)
if person.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
elsif player_cur_location.contains_item?(talkable_name)
player_cur_location.items.each do |person|
if person.name.eql?(talkable_name)
if person.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
elsif player_cur_location.has_monster?(talkable_name)
player_cur_location.monsters_abounding.each do |monster|
if monster.name.eql?(talkable_name)
if monster.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
elsif player_cur_location.has_boss?(talkable_name)
player_cur_location.bosses_abounding.each do |boss|
if boss.name.eql?(talkable_name)
if boss.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
end
when 'use', 'u'
if param1.nil?
ERROR_USE_PARAM_MISSING
else
item_name = param1
result = nil
player_inventory = world.player.inventory
if player_inventory.contains_item?(item_name)
player_inventory.items.each do |i|
if i.name.eql?(item_name)
if i.useable
if !i.number_of_uses.nil?
if i.number_of_uses > 0
result = i.use(world)
i.number_of_uses -= 1
puts ">> #{i.name} can be used #{i.number_of_uses} more time(s)."
break
else
return ">> #{i.name} cannot be used anymore."
end
elsif i.consumable
result = i.use(world)
world.player.inventory.remove_item(i.name)
break
else
result = i.use(world)
break
end
else
return ERROR_USE_PARAM_UNUSEABLE
end
end
end
elsif player_cur_location.contains_item?(item_name)
player_cur_location.items.each do |i|
if i.name.eql?(item_name)
if i.useable
if !i.number_of_uses.nil?
if i.number_of_uses > 0
result = i.use(world)
i.number_of_uses -= 1
puts ">> #{i.name} can be used #{i.number_of_uses} more time(s)."
break
else
return ">> #{i.name} cannot be used anymore."
end
elsif i.consumable
result = i.use(world)
location.remove_item(i.name)
break
else
result = i.use(world)
break
end
else
return ERROR_USE_PARAM_UNUSEABLE
end
end
end
elsif player_cur_location.has_monster?(item_name)
player_cur_location.monsters_abounding.each do |i|
if i.name.eql?(item_name)
return i.use(world)
end
end
elsif player_cur_location.has_boss?(item_name)
player_cur_location.bosses_abounding.each do |i|
if i.name.eql?(item_name)
return i.use(world)
end
end
end
if result.nil?
ERROR_USE_PARAM_INVALID
else
case result[:type]
when 'move'
world.player.cur_coords = world.location_coords_by_name(result[:data])
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
when 'move_dangerous'
dmg = rand(0..2)
puts ">> You lose #{dmg} hit point(s)." if dmg > 0
world.player.take_damage(dmg)
world.player.cur_coords = world.location_coords_by_name(result[:data])
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
when 'dmg'
world.player.take_damage(result[:data])
return
when 'rest', 'health'
world.player.heal_damage(result[:data])
return
when 'xp'
world.player.update_stats(reason: :xp, value: result[:data])
return
when 'tent'
world.player.rest(world, result[:data])
when 'action'
case result[:data]
when 'map'
world.print_map(world.player.cur_coords[:z])
end
when 'arena'
arena = Arena.new(world: world, player: world.player)
result = arena.start
if result.eql?('death')
player_death_resurrection
end
when 'item'
player_cur_location.add_item(result[:data])
return
when 'purchase'
result[:data].each do |i|
world.player.inventory.items.push(i)
end
return
else
return
end
end
end
when 'drop', 'd'
if param1.nil?
ERROR_DROP_PARAM_MISSING
else
world.player.inventory.drop_item(param1, player_cur_location)
end
when 'equip', 'eq'
if param1.nil?
ERROR_EQUIP_PARAM_MISSING
else
world.player.inventory.equip_item(param1)
end
when 'unequip', 'ue'
if param1.nil?
ERROR_UNEQUIP_PARAM_MISSING
else
world.player.inventory.unequip_item(param1)
end
when 'go', 'g'
if param1.nil?
puts ERROR_GO_PARAM_MISSING
GO_PARAMS
else
direction = param1
try_to_move_player(direction)
end
when 'n'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('north')
end
when 'e'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('east')
end
when 's'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('south')
end
when 'w'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('west')
end
when 'attack', 'a', 'fight', 'f'
if param1.nil?
ERROR_ATTACK_PARAM_MISSING
else
monster_name = param1
if world.has_monster_to_attack?(monster_name)
monster = player_cur_location.monster_by_name(monster_name)
result = world.player.attack(world, monster)
if result.eql?('death')
return player_death_resurrection
elsif result.eql?('exit')
return 'exit'
end
unless result.nil?
case result[:type]
when 'message'
result[:data]
when 'move'
world.player.cur_coords = world.location_coords_by_name(result[:data])
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
end
end
else
ERROR_ATTACK_PARAM_INVALID
end
end
when 'change', 'ch'
if param1.nil?
puts ERROR_CHANGE_PARAM_MISSING
CHANGE_PARAMS
else
case param1
when 'name'
world.player.modify_name
else
ERROR_CHANGE_PARAM_INVALID
end
end
when 'help', 'h', '?', '??', '???'
list_commands
when 'version', 'v'
Gemwarrior::VERSION
when 'checkupdate', 'cu'
'checkupdate'
when 'quit', 'exit', 'q', 'x'
print 'You sure you want to quit? (y/n) '
answer = gets.chomp.downcase
case answer
when 'y', 'yes'
puts QUIT_MESSAGE
return 'exit'
else
puts RESUME_MESSAGE
end
when 'quit!', 'exit!', 'qq', 'xx'
puts QUIT_MESSAGE
return 'exit'
else
return
end
end
private
def try_to_move_player(direction)
if world.can_move?(direction)
world.player.go(world.locations, direction)
player_cur_location = world.location_by_coords(world.player.cur_coords)
player_cur_location.checked_for_monsters = false
world.describe(player_cur_location)
else
return ERROR_GO_PARAM_INVALID.colorize(:red)
end
end
def player_death_resurrection
Audio.play_synth(:player_resurrection)
puts 'Somehow, though, your adventure does not end here!'.colorize(:yellow)
puts 'Instead, you are whisked back home via some magical force.'.colorize(:yellow)
puts 'A bit worse for the weary and somewhat poorer, but you are ALIVE!'.colorize(:yellow)
puts
world.player.hp_cur = 1
world.player.rox -= (world.player.rox * 0.1).to_i
if world.player.rox < 0
world.player.rox = 0
end
world.player.cur_coords = world.location_coords_by_name('Home')
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
world.player.deaths += 1
return
end
def list_commands
i = 0
Hr.print('=')
puts ' COMMAND | ALIAS | DESCRIPTION '
Hr.print('=')
commands.each do |cmd|
puts " #{cmd.ljust(11)} | #{aliases[i].ljust(5)} | #{cmd_descriptions[i]}"
i += 1
end
Hr.print('=')
if GameOptions.data['debug_mode']
puts ' DEBUG COMMANDS'
Hr.print('=')
i = 0
devcommands.each do |cmd|
puts " #{cmd.ljust(11)} | #{devaliases[i].ljust(5)} | #{devcmd_descriptions[i]}"
i += 1
end
Hr.print('=')
end
end
def input_valid?(input)
tokens = input.split
command = tokens[0]
commands_and_aliases = commands | aliases | extras
if GameOptions.data['debug_mode']
commands_and_aliases = commands_and_aliases | devcommands | devaliases | devextras
end
if commands_and_aliases.include?(command.downcase)
if tokens.size.between?(1, 4)
return true
end
elsif tokens.empty?
return true
end
end
end
end
moved some colorization to usage, not declaration
# lib/gemwarrior/evaluator.rb
# Evaluates prompt input
require_relative 'arena'
require_relative 'game_assets'
require_relative 'game_options'
module Gemwarrior
class Evaluator
# CONSTANTS
PROGRAM_NAME = 'Gem Warrior'
QUIT_MESSAGE = 'Thanks for playing the game. Until next time...'
RESUME_MESSAGE = 'Back to adventuring!'
GO_PARAMS = 'Options: north, east, south, west'
CHANGE_PARAMS = 'Options: name'
DEBUG_LIST_PARAMS = 'Options: players, creatures, items, locations, monsters, weapons'
DEBUG_STAT_PARAMS = 'Options: hp_cur, atk_lo, atk_hi, experience, rox, strength, dexterity, defense, inventory'
ERROR_COMMAND_INVALID = 'That is not something the game yet understands.'
ERROR_LOOK_AT_PARAM_MISSING = 'You cannot just "look at". You gotta choose something to look at.'
ERROR_TALK_PARAM_INVALID = 'Are you talking to yourself? That person is not here.'
ERROR_TALK_PARAM_UNTALKABLE = 'That cannnot be conversed with.'
ERROR_TALK_TO_PARAM_MISSING = 'You cannot just "talk to". You gotta choose someone to talk to.'
ERROR_GO_PARAM_MISSING = 'Just wander aimlessly? A direction would be nice.'
ERROR_GO_PARAM_INVALID = 'Something tells you that is not a way to go.'
ERROR_DIRECTION_PARAM_INVALID = 'You cannot go to that place.'
ERROR_ATTACK_PARAM_MISSING = 'You cannot just "attack". You gotta choose something to attack.'
ERROR_ATTACK_PARAM_INVALID = 'That monster does not exist here or can\'t be attacked.'
ERROR_TAKE_PARAM_MISSING = 'You cannot just "take". You gotta choose something to take.'
ERROR_USE_PARAM_MISSING = 'You cannot just "use". You gotta choose something to use.'
ERROR_USE_PARAM_INVALID = 'You cannot use that, as it does not exist here or in your inventory.'
ERROR_USE_PARAM_UNUSEABLE = 'That is not useable.'
ERROR_DROP_PARAM_MISSING = 'You cannot just "drop". You gotta choose something to drop.'
ERROR_EQUIP_PARAM_MISSING = 'You cannot just "equip". You gotta choose something to equip.'
ERROR_UNEQUIP_PARAM_MISSING = 'You cannot just "unequip". You gotta choose something to unequip.'
ERROR_CHANGE_PARAM_MISSING = 'You cannot just "change". You gotta choose something to change.'
ERROR_CHANGE_PARAM_INVALID = 'You cannot change that...yet.'
ERROR_LIST_PARAM_MISSING = 'You cannot just "list". You gotta choose something to list.'
ERROR_LIST_PARAM_INVALID = 'You cannot list that...yet.'
ERROR_DEBUG_STAT_PARAM_MISSING = 'You cannot just "change stats". You gotta choose a stat to change.'
ERROR_DEBUG_STAT_PARAM_INVALID = 'You cannot change that stat...yet.'
ERROR_DEBUG_STAT_INV_PARAM_INVALID = 'You cannot add that to your inventory...yet.'
ERROR_DEBUG_GLOBAL_VAR_INVALID = 'That global variable does not exist.'
ERROR_DEBUG_TELEPORT_PARAMS_MISSING = 'You cannot just "teleport". You gotta specify an x AND y coordinate, at least.'
ERROR_DEBUG_TELEPORT_PARAMS_NEEDED = 'You cannot just "teleport" to an x coordinate without a y coordinate.'
ERROR_DEBUG_TELEPORT_PARAMS_INVALID = 'You cannot teleport there...yet.'
attr_accessor :world,
:commands,
:aliases,
:extras,
:cmd_descriptions,
:devcommands,
:devaliases,
:devextras,
:devcmd_descriptions
def initialize(world)
self.world = world
self.devcommands = %w(god beast constants list vars map stat global teleport spawn levelbump restfight)
self.devaliases = %w(gd bs cn ls vs m st gl tp sp lb rf)
self.devextras = %w()
self.devcmd_descriptions = [
'Toggle god mode (i.e. invincible)',
'Toggle beast mode (i.e. super strength)',
'List all GameAssets',
'List all instances of a specific entity type',
'List all the variables in the world',
'Show a map of the world',
'Change player stat',
'Change world global variable',
'Teleport to coordinates (5 0 0) or name (\'Home\')',
'Spawn random monster',
'Bump your character up *n* levels',
'Rest, but ensure battle for testing'
]
self.commands = %w(character look rest take talk inventory use drop equip unequip go north east south west attack change version checkupdate help quit quit!)
self.aliases = %w(c l r t tk i u d eq ue g n e s w a ch v cu h q qq)
self.extras = %w(exit exit! x xx fight f ? ?? ???)
self.cmd_descriptions = [
'Display character information',
'Look around your current location',
'Take a load off and regain HP',
'Take item',
'Talk to person',
'Look in your inventory',
'Use item (in inventory or environment)',
'Drop item',
'Equip item',
'Unequip item',
'Go in a direction',
'Go north (shortcut)',
'Go east (shortcut)',
'Go south (shortcut)',
'Go west (shortcut)',
'Attack a monster (also fight)',
'Change attribute',
'Display game version',
'Check for newer game releases',
'This help menu (also ?)',
'Quit w/ confirmation (also exit/x)',
'Quit w/o confirmation (also exit!/xx)'
]
end
def parse(input)
case input
# Ctrl-D or empty command
when nil, ''
return
# real command
else
return ERROR_COMMAND_INVALID.colorize(:red) unless input_valid?(input)
end
tokens = input.split
command = tokens.first.downcase
param1 = tokens[1]
param2 = tokens[2]
param3 = tokens[3]
# helpful
player_cur_location = world.location_by_coords(world.player.cur_coords)
# dev commands
if GameOptions.data['debug_mode']
case command
when 'god', 'gd'
GameOptions.data['god_mode'] = !GameOptions.data['god_mode']
return "God mode set to #{GameOptions.data['god_mode']}"
when 'beast', 'bs'
GameOptions.data['beast_mode'] = !GameOptions.data['beast_mode']
return "Beast mode set to #{GameOptions.data['beast_mode']}"
when 'constants', 'cn'
puts 'GameCreatures'.colorize(:yellow)
puts GameCreatures.data
STDIN.getc
puts 'GameMonsters'.colorize(:yellow)
puts GameMonsters.data
STDIN.getc
puts 'GamePeople'.colorize(:yellow)
puts GamePeople.data
STDIN.getc
puts 'GameItems'.colorize(:yellow)
puts GameItems.data
STDIN.getc
puts 'GameArmor'.colorize(:yellow)
puts GameArmor.data
STDIN.getc
puts 'GameWeapons'.colorize(:yellow)
puts GameWeapons.data
when 'vars', 'vs'
if param1
world.print_vars(param1)
else
world.print_vars
end
when 'list', 'ls'
if param1.nil?
puts ERROR_LIST_PARAM_MISSING
return DEBUG_LIST_PARAMS
else
return world.list(param1, param2)
end
when 'map', 'm'
world.print_map(param1)
when 'stat', 'st'
if param1.nil?
puts ERROR_DEBUG_STAT_PARAM_MISSING
return DEBUG_STAT_PARAMS
else
case param1
when 'hp_cur', 'hp'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 > 0
world.player.hp_cur = param2
end
end
end
when 'atk_lo'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.atk_lo = param2
end
end
end
when 'atk_hi'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.atk_hi = param2
end
end
end
when 'strength', 'str', 'st'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.atk_lo = param2
world.player.atk_hi = param2
end
end
end
when 'dexterity', 'dex'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.dexterity = param2
end
end
end
when 'defense', 'def'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.defense = param2
end
end
end
when 'rox', 'r', '$'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.rox = param2
end
end
end
when 'experience', 'xp'
unless param2.nil?
param2 = param2.to_i
if param2.is_a? Numeric
if param2 >= 0
world.player.xp = param2
end
end
end
when 'inventory', 'inv'
unless param2.nil?
begin
item_const_name = Gemwarrior.const_get(Formatting.upstyle(param2, no_space: true))
item = item_const_name.new
world.player.inventory.items.push(item)
return "#{item.name} added to player inventory."
rescue
return ERROR_DEBUG_STAT_INV_PARAM_INVALID
end
end
else
return ERROR_DEBUG_STAT_PARAM_INVALID
end
end
when 'global', 'gl'
if param1.nil?
return world.instance_variables.join(', ')
elsif world.instance_variable_get("@#{param1}").nil?
return ERROR_DEBUG_GLOBAL_VAR_INVALID
elsif param2.nil?
return world.instance_variable_get("@#{param1}").to_s
else
val = false
val = param2.eql?('true') ? true : val
world.instance_variable_set("@#{param1}", val)
return "Instance variable #{param1} has been set to #{val}."
end
when 'spawn', 'sp'
player_cur_location = world.location_by_coords(world.player.cur_coords)
player_cur_location.populate_monsters(GameMonsters.data, spawn: true)
return world.describe(player_cur_location)
when 'teleport', 'tp'
if param1.nil?
return ERROR_DEBUG_TELEPORT_PARAMS_MISSING
else
if (param1.to_i.to_s == param1)
# we got at least an x coordinate
if (param2.to_i.to_s == param2)
# we got a y coordinate, too
x_coord = param1.to_i
y_coord = param2.to_i
# grab the z coordinate, if present, otherwise default to current level
z_coord = param3.to_i.to_s == param3 ? param3.to_i : world.player.cur_coords[:z]
# check to make sure new location exists
if world.location_by_coords(x: x_coord, y: y_coord, z: z_coord)
world.player.cur_coords = { x: x_coord, y: y_coord, z: z_coord }
else
return ERROR_DEBUG_TELEPORT_PARAMS_INVALID
end
else
# we only got an x coordinate
return ERROR_DEBUG_TELEPORT_PARAMS_NEEDED
end
else
# we got a place name instead, potentially
place_to_match = tokens[1..tokens.length].join(' ').downcase
locations = []
world.locations.each do |l|
locations << l.name.downcase
end
if locations.include?(place_to_match)
world.player.cur_coords = world.location_coords_by_name(place_to_match)
else
return ERROR_DEBUG_TELEPORT_PARAMS_INVALID
end
end
# stats
world.player.movements_made += 1
Animation.run(phrase: '** TELEPORT! **', speed: :insane)
player_cur_location = world.location_by_coords(world.player.cur_coords)
return world.describe(player_cur_location)
end
when 'levelbump', 'lb'
new_level = param1.nil? ? 1 : param1.to_i
world.player.update_stats(reason: :level_bump, value: new_level)
when 'restfight', 'rf'
result = world.player.rest(world, 0, true)
if result.eql?('death')
player_death_resurrection
end
end
end
# normal commands
case command
when 'character', 'c'
# bypass puts so it prints out with newlines properly
print world.player.check_self
when 'inventory', 'i'
if param1
world.player.inventory.describe_item(param1)
else
world.player.list_inventory
end
when 'look', 'l'
if param1
# convert 'look at' to 'look'
if param1.eql?('at')
if param2
param1 = param2
else
return ERROR_LOOK_AT_PARAM_MISSING
end
end
world.describe_entity(player_cur_location, param1)
else
world.describe(player_cur_location)
end
when 'rest', 'r'
tent_uses = 0
player_inventory = world.player.inventory
if player_inventory.contains_item?('tent')
player_inventory.items.each do |i|
if i.name.eql?('tent')
if i.number_of_uses > 0
result = i.use(world)
tent_uses = i.number_of_uses
i.number_of_uses -= 1
puts ">> tent can be used when resting #{i.number_of_uses} more time(s)."
end
end
end
elsif player_cur_location.contains_item?('tent')
player_cur_location.items.each do |i|
if i.name.eql?('tent')
if i.number_of_uses > 0
result = i.use(world)
tent_uses = i.number_of_uses
i.number_of_uses -= 1
puts ">> tent can be used when resting #{i.number_of_uses} more time(s)."
end
end
end
end
result = world.player.rest(world, tent_uses)
if result.eql?('death')
player_death_resurrection
else
result
end
when 'take', 't'
if param1.nil?
ERROR_TAKE_PARAM_MISSING
else
world.player.inventory.add_item(param1, player_cur_location, world.player)
end
when 'talk', 'tk'
if param1.nil?
return ERROR_TALK_TO_PARAM_MISSING
elsif param1.eql?('to')
if param2
param1 = param2
else
return ERROR_TALK_TO_PARAM_MISSING
end
end
talkable_name = param1
player_inventory = world.player.inventory
if player_inventory.contains_item?(talkable_name)
player_inventory.items.each do |person|
if person.name.eql?(talkable_name)
if person.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
elsif player_cur_location.contains_item?(talkable_name)
player_cur_location.items.each do |person|
if person.name.eql?(talkable_name)
if person.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
elsif player_cur_location.has_monster?(talkable_name)
player_cur_location.monsters_abounding.each do |monster|
if monster.name.eql?(talkable_name)
if monster.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
elsif player_cur_location.has_boss?(talkable_name)
player_cur_location.bosses_abounding.each do |boss|
if boss.name.eql?(talkable_name)
if boss.talkable
return self.parse("use #{talkable_name}")
else
return ERROR_TALK_PARAM_UNTALKABLE
end
end
end
end
when 'use', 'u'
if param1.nil?
ERROR_USE_PARAM_MISSING
else
item_name = param1
result = nil
player_inventory = world.player.inventory
if player_inventory.contains_item?(item_name)
player_inventory.items.each do |i|
if i.name.eql?(item_name)
if i.useable
if !i.number_of_uses.nil?
if i.number_of_uses > 0
result = i.use(world)
i.number_of_uses -= 1
puts ">> #{i.name} can be used #{i.number_of_uses} more time(s)."
break
else
return ">> #{i.name} cannot be used anymore."
end
elsif i.consumable
result = i.use(world)
world.player.inventory.remove_item(i.name)
break
else
result = i.use(world)
break
end
else
return ERROR_USE_PARAM_UNUSEABLE
end
end
end
elsif player_cur_location.contains_item?(item_name)
player_cur_location.items.each do |i|
if i.name.eql?(item_name)
if i.useable
if !i.number_of_uses.nil?
if i.number_of_uses > 0
result = i.use(world)
i.number_of_uses -= 1
puts ">> #{i.name} can be used #{i.number_of_uses} more time(s)."
break
else
return ">> #{i.name} cannot be used anymore."
end
elsif i.consumable
result = i.use(world)
location.remove_item(i.name)
break
else
result = i.use(world)
break
end
else
return ERROR_USE_PARAM_UNUSEABLE
end
end
end
elsif player_cur_location.has_monster?(item_name)
player_cur_location.monsters_abounding.each do |i|
if i.name.eql?(item_name)
return i.use(world)
end
end
elsif player_cur_location.has_boss?(item_name)
player_cur_location.bosses_abounding.each do |i|
if i.name.eql?(item_name)
return i.use(world)
end
end
end
if result.nil?
ERROR_USE_PARAM_INVALID
else
case result[:type]
when 'move'
world.player.cur_coords = world.location_coords_by_name(result[:data])
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
when 'move_dangerous'
dmg = rand(0..2)
puts ">> You lose #{dmg} hit point(s)." if dmg > 0
world.player.take_damage(dmg)
world.player.cur_coords = world.location_coords_by_name(result[:data])
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
when 'dmg'
world.player.take_damage(result[:data])
return
when 'rest', 'health'
world.player.heal_damage(result[:data])
return
when 'xp'
world.player.update_stats(reason: :xp, value: result[:data])
return
when 'tent'
world.player.rest(world, result[:data])
when 'action'
case result[:data]
when 'map'
world.print_map(world.player.cur_coords[:z])
end
when 'arena'
arena = Arena.new(world: world, player: world.player)
result = arena.start
if result.eql?('death')
player_death_resurrection
end
when 'item'
player_cur_location.add_item(result[:data])
return
when 'purchase'
result[:data].each do |i|
world.player.inventory.items.push(i)
end
return
else
return
end
end
end
when 'drop', 'd'
if param1.nil?
ERROR_DROP_PARAM_MISSING
else
world.player.inventory.drop_item(param1, player_cur_location)
end
when 'equip', 'eq'
if param1.nil?
ERROR_EQUIP_PARAM_MISSING
else
world.player.inventory.equip_item(param1)
end
when 'unequip', 'ue'
if param1.nil?
ERROR_UNEQUIP_PARAM_MISSING
else
world.player.inventory.unequip_item(param1)
end
when 'go', 'g'
if param1.nil?
puts ERROR_GO_PARAM_MISSING
GO_PARAMS
else
direction = param1
try_to_move_player(direction)
end
when 'n'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('north')
end
when 'e'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('east')
end
when 's'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('south')
end
when 'w'
if param1
ERROR_DIRECTION_PARAM_INVALID
else
try_to_move_player('west')
end
when 'attack', 'a', 'fight', 'f'
if param1.nil?
ERROR_ATTACK_PARAM_MISSING
else
monster_name = param1
if world.has_monster_to_attack?(monster_name)
monster = player_cur_location.monster_by_name(monster_name)
result = world.player.attack(world, monster)
if result.eql?('death')
return player_death_resurrection
elsif result.eql?('exit')
return 'exit'
end
unless result.nil?
case result[:type]
when 'message'
result[:data]
when 'move'
world.player.cur_coords = world.location_coords_by_name(result[:data])
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
end
end
else
ERROR_ATTACK_PARAM_INVALID
end
end
when 'change', 'ch'
if param1.nil?
puts ERROR_CHANGE_PARAM_MISSING
CHANGE_PARAMS
else
case param1
when 'name'
world.player.modify_name
else
ERROR_CHANGE_PARAM_INVALID
end
end
when 'help', 'h', '?', '??', '???'
list_commands
when 'version', 'v'
Gemwarrior::VERSION
when 'checkupdate', 'cu'
'checkupdate'
when 'quit', 'exit', 'q', 'x'
print 'You sure you want to quit? (y/n) '
answer = gets.chomp.downcase
case answer
when 'y', 'yes'
puts QUIT_MESSAGE.colorize(:yellow)
return 'exit'
else
puts RESUME_MESSAGE.colorize(:green)
end
when 'quit!', 'exit!', 'qq', 'xx'
puts QUIT_MESSAGE.colorize(:yellow)
return 'exit'
else
return
end
end
private
def try_to_move_player(direction)
if world.can_move?(direction)
world.player.go(world.locations, direction)
player_cur_location = world.location_by_coords(world.player.cur_coords)
player_cur_location.checked_for_monsters = false
world.describe(player_cur_location)
else
return ERROR_GO_PARAM_INVALID.colorize(:red)
end
end
def player_death_resurrection
Audio.play_synth(:player_resurrection)
puts 'Somehow, though, your adventure does not end here!'.colorize(:yellow)
puts 'Instead, you are whisked back home via some magical force.'.colorize(:yellow)
puts 'A bit worse for the weary and somewhat poorer, but you are ALIVE!'.colorize(:yellow)
puts
world.player.hp_cur = 1
world.player.rox -= (world.player.rox * 0.1).to_i
if world.player.rox < 0
world.player.rox = 0
end
world.player.cur_coords = world.location_coords_by_name('Home')
player_cur_location = world.location_by_coords(world.player.cur_coords)
world.describe(player_cur_location)
world.player.deaths += 1
return
end
def list_commands
i = 0
Hr.print('=')
puts ' COMMAND | ALIAS | DESCRIPTION '
Hr.print('=')
commands.each do |cmd|
puts " #{cmd.ljust(11)} | #{aliases[i].ljust(5)} | #{cmd_descriptions[i]}"
i += 1
end
Hr.print('=')
if GameOptions.data['debug_mode']
puts ' DEBUG COMMANDS'
Hr.print('=')
i = 0
devcommands.each do |cmd|
puts " #{cmd.ljust(11)} | #{devaliases[i].ljust(5)} | #{devcmd_descriptions[i]}"
i += 1
end
Hr.print('=')
end
end
def input_valid?(input)
tokens = input.split
command = tokens[0]
commands_and_aliases = commands | aliases | extras
if GameOptions.data['debug_mode']
commands_and_aliases = commands_and_aliases | devcommands | devaliases | devextras
end
if commands_and_aliases.include?(command.downcase)
if tokens.size.between?(1, 4)
return true
end
elsif tokens.empty?
return true
end
end
end
end
|
require 'helper'
class TestParsing < Test::Unit::TestCase
# Wed Aug 16 14:00:00 UTC 2006
TIME_2006_08_16_14_00_00 = Time.local(2006, 8, 16, 14, 0, 0, 0)
def setup
@time_2006_08_16_14_00_00 = TIME_2006_08_16_14_00_00
end
def test_handle_rmn_sd
time = parse_now("aug 3")
assert_equal Time.local(2006, 8, 3, 12), time
time = parse_now("aug 3", :context => :past)
assert_equal Time.local(2006, 8, 3, 12), time
time = parse_now("aug 20")
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("aug 20", :context => :future)
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("may 27")
assert_equal Time.local(2007, 5, 27, 12), time
time = parse_now("may 28", :context => :past)
assert_equal Time.local(2006, 5, 28, 12), time
time = parse_now("may 28 5pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17), time
time = parse_now("may 28 at 5pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17), time
time = parse_now("may 28 at 5:32.19pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17, 32, 19), time
end
def test_handle_rmn_sd_on
time = parse_now("5pm on may 28")
assert_equal Time.local(2007, 5, 28, 17), time
time = parse_now("5pm may 28")
assert_equal Time.local(2007, 5, 28, 17), time
time = parse_now("5 on may 28", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 28, 05), time
end
def test_handle_rmn_od
time = parse_now("may 27th")
assert_equal Time.local(2007, 5, 27, 12), time
time = parse_now("may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 12), time
time = parse_now("may 27th 5:00 pm", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("may 27th at 5pm", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("may 27th at 5", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 27, 5), time
end
def test_handle_od_rmn
time = parse_now("22nd February")
assert_equal Time.local(2007, 2, 22, 12), time
time = parse_now("31st of may at 6:30pm")
assert_equal Time.local(2007, 5, 31, 18, 30), time
time = parse_now("11th december 8am")
assert_equal Time.local(2006, 12, 11, 8), time
end
def test_handle_sy_rmn_od
time = parse_now("2009 May 22nd")
assert_equal Time.local(2009, 05, 22, 12), time
end
def test_handle_sd_rmn
time = parse_now("22 February")
assert_equal Time.local(2007, 2, 22, 12), time
time = parse_now("31 of may at 6:30pm")
assert_equal Time.local(2007, 5, 31, 18, 30), time
time = parse_now("11 december 8am")
assert_equal Time.local(2006, 12, 11, 8), time
end
def test_handle_rmn_od_on
time = parse_now("5:00 pm may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("05:00 pm may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("5pm on may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("5 on may 27th", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 27, 5), time
end
def test_handle_rmn_sy
time = parse_now("may 97")
assert_equal Time.local(1997, 5, 16, 12), time
time = parse_now("may 33", :ambiguous_year_future_bias => 10)
assert_equal Time.local(2033, 5, 16, 12), time
time = parse_now("may 32")
assert_equal Time.local(2032, 5, 16, 12, 0, 0), time
end
def test_handle_rdn_rmn_sd_t_tz_sy
time = parse_now("Mon Apr 02 17:00:00 PDT 2007")
assert_equal 1175558400, time.to_i
end
def test_handle_sy_sm_sd_t_tz
time = parse_now("2011-07-03 22:11:35 +0100")
assert_equal 1309727495, time.to_i
time = parse_now("2011-07-03 22:11:35 +01:00")
assert_equal 1309727495, time.to_i
time = parse_now("2011-07-03 21:11:35 UTC")
assert_equal 1309727495, time.to_i
end
def test_handle_rmn_sd_sy
time = parse_now("November 18, 2010")
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("Jan 1,2010")
assert_equal Time.local(2010, 1, 1, 12), time
time = parse_now("February 14, 2004")
assert_equal Time.local(2004, 2, 14, 12), time
time = parse_now("jan 3 2010")
assert_equal Time.local(2010, 1, 3, 12), time
time = parse_now("jan 3 2010 midnight")
assert_equal Time.local(2010, 1, 4, 0), time
time = parse_now("jan 3 2010 at midnight")
assert_equal Time.local(2010, 1, 4, 0), time
time = parse_now("jan 3 2010 at 4", :ambiguous_time_range => :none)
assert_equal Time.local(2010, 1, 3, 4), time
time = parse_now("may 27, 1979")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("may 27 79")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("may 27 79 4:30")
assert_equal Time.local(1979, 5, 27, 16, 30), time
time = parse_now("may 27 79 at 4:30", :ambiguous_time_range => :none)
assert_equal Time.local(1979, 5, 27, 4, 30), time
time = parse_now("may 27 32")
assert_equal Time.local(2032, 5, 27, 12, 0, 0), time
end
def test_handle_rmn_od_sy
time = parse_now("may 1st 01")
assert_equal Time.local(2001, 5, 1, 12), time
time = parse_now("November 18th 2010")
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("November 18th, 2010")
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("November 18th 2010 midnight")
assert_equal Time.local(2010, 11, 19, 0), time
time = parse_now("November 18th 2010 at midnight")
assert_equal Time.local(2010, 11, 19, 0), time
time = parse_now("November 18th 2010 at 4")
assert_equal Time.local(2010, 11, 18, 16), time
time = parse_now("November 18th 2010 at 4", :ambiguous_time_range => :none)
assert_equal Time.local(2010, 11, 18, 4), time
time = parse_now("March 30th, 1979")
assert_equal Time.local(1979, 3, 30, 12), time
time = parse_now("March 30th 79")
assert_equal Time.local(1979, 3, 30, 12), time
time = parse_now("March 30th 79 4:30")
assert_equal Time.local(1979, 3, 30, 16, 30), time
time = parse_now("March 30th 79 at 4:30", :ambiguous_time_range => :none)
assert_equal Time.local(1979, 3, 30, 4, 30), time
end
def test_handle_od_rmn_sy
time = parse_now("22nd February 2012")
assert_equal Time.local(2012, 2, 22, 12), time
time = parse_now("11th december 79")
assert_equal Time.local(1979, 12, 11, 12), time
end
def test_handle_sd_rmn_sy
time = parse_now("3 jan 2010")
assert_equal Time.local(2010, 1, 3, 12), time
time = parse_now("3 jan 2010 4pm")
assert_equal Time.local(2010, 1, 3, 16), time
time = parse_now("27 Oct 2006 7:30pm")
assert_equal Time.local(2006, 10, 27, 19, 30), time
end
def test_handle_sm_sd_sy
time = parse_now("5/27/1979")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("5/27/1979 4am")
assert_equal Time.local(1979, 5, 27, 4), time
time = parse_now("7/12/11")
assert_equal Time.local(2011, 7, 12, 12), time
time = parse_now("7/12/11", :endian_precedence => :little)
assert_equal Time.local(2011, 12, 7, 12), time
time = parse_now("9/19/2011 6:05:57 PM")
assert_equal Time.local(2011, 9, 19, 18, 05, 57), time
# month day overflows
time = parse_now("30/2/2000")
assert_nil time
end
def test_handle_sd_sm_sy
time = parse_now("27/5/1979")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("27/5/1979 @ 0700")
assert_equal Time.local(1979, 5, 27, 7), time
end
def test_handle_sy_sm_sd
time = parse_now("2000-1-1")
assert_equal Time.local(2000, 1, 1, 12), time
time = parse_now("2006-08-20")
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("2006-08-20 7pm")
assert_equal Time.local(2006, 8, 20, 19), time
time = parse_now("2006-08-20 03:00")
assert_equal Time.local(2006, 8, 20, 3), time
time = parse_now("2006-08-20 03:30:30")
assert_equal Time.local(2006, 8, 20, 3, 30, 30), time
time = parse_now("2006-08-20 15:30:30")
assert_equal Time.local(2006, 8, 20, 15, 30, 30), time
time = parse_now("2006-08-20 15:30.30")
assert_equal Time.local(2006, 8, 20, 15, 30, 30), time
time = parse_now("1902-08-20")
assert_equal Time.local(1902, 8, 20, 12, 0, 0), time
end
def test_handle_sm_sy
time = parse_now("05/06")
assert_equal Time.local(2006, 5, 16, 12), time
time = parse_now("12/06")
assert_equal Time.local(2006, 12, 16, 12), time
time = parse_now("13/06")
assert_equal nil, time
end
def test_handle_r
end
def test_handle_r_g_r
end
def test_handle_srp
end
def test_handle_s_r_p
end
def test_handle_p_s_r
end
def test_handle_s_r_p_a
end
def test_handle_orr
time = parse_now("5th tuesday in january")
assert_equal Time.local(2007, 01, 30, 12), time
time = parse_now("5th tuesday in february")
assert_equal nil, time
end
def test_handle_o_r_s_r
time = parse_now("3rd wednesday in november")
assert_equal Time.local(2006, 11, 15, 12), time
time = parse_now("10th wednesday in november")
assert_equal nil, time
# time = parse_now("3rd wednesday in 2007")
# assert_equal Time.local(2007, 1, 20, 12), time
end
def test_handle_o_r_g_r
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3), time.begin
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3, 1), time.begin
time = parse_now("3rd thursday this september")
assert_equal Time.local(2006, 9, 21, 12), time
now = Time.parse("1/10/2010")
time = parse_now("3rd thursday this november", :now => now)
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("4th day last week")
assert_equal Time.local(2006, 8, 9, 12), time
end
# end of testing handlers
def test_parse_guess_r
time = parse_now("friday")
assert_equal Time.local(2006, 8, 18, 12), time
time = parse_now("tue")
assert_equal Time.local(2006, 8, 22, 12), time
time = parse_now("5")
assert_equal Time.local(2006, 8, 16, 17), time
time = Chronic.parse("5", :now => Time.local(2006, 8, 16, 3, 0, 0, 0), :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 16, 5), time
time = parse_now("13:00")
assert_equal Time.local(2006, 8, 17, 13), time
time = parse_now("13:45")
assert_equal Time.local(2006, 8, 17, 13, 45), time
time = parse_now("1:01pm")
assert_equal Time.local(2006, 8, 16, 13, 01), time
time = parse_now("2:01pm")
assert_equal Time.local(2006, 8, 16, 14, 01), time
time = parse_now("november")
assert_equal Time.local(2006, 11, 16), time
end
def test_parse_guess_rr
time = parse_now("friday 13:00")
assert_equal Time.local(2006, 8, 18, 13), time
time = parse_now("monday 4:00")
assert_equal Time.local(2006, 8, 21, 16), time
time = parse_now("sat 4:00", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 19, 4), time
time = parse_now("sunday 4:20", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 20, 4, 20), time
time = parse_now("4 pm")
assert_equal Time.local(2006, 8, 16, 16), time
time = parse_now("4 am", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 16, 4), time
time = parse_now("12 pm")
assert_equal Time.local(2006, 8, 16, 12), time
time = parse_now("12:01 pm")
assert_equal Time.local(2006, 8, 16, 12, 1), time
time = parse_now("12:01 am")
assert_equal Time.local(2006, 8, 16, 0, 1), time
time = parse_now("12 am")
assert_equal Time.local(2006, 8, 16), time
time = parse_now("4:00 in the morning")
assert_equal Time.local(2006, 8, 16, 4), time
time = parse_now("0:10")
assert_equal Time.local(2006, 8, 17, 0, 10), time
time = parse_now("november 4")
assert_equal Time.local(2006, 11, 4, 12), time
time = parse_now("aug 24")
assert_equal Time.local(2006, 8, 24, 12), time
end
def test_parse_guess_rrr
time = parse_now("friday 1 pm")
assert_equal Time.local(2006, 8, 18, 13), time
time = parse_now("friday 11 at night")
assert_equal Time.local(2006, 8, 18, 23), time
time = parse_now("friday 11 in the evening")
assert_equal Time.local(2006, 8, 18, 23), time
time = parse_now("sunday 6am")
assert_equal Time.local(2006, 8, 20, 6), time
time = parse_now("friday evening at 7")
assert_equal Time.local(2006, 8, 18, 19), time
end
def test_parse_guess_gr
# year
time = parse_now("this year", :guess => false)
assert_equal Time.local(2006, 8, 17), time.begin
time = parse_now("this year", :context => :past, :guess => false)
assert_equal Time.local(2006, 1, 1), time.begin
# month
time = parse_now("this month")
assert_equal Time.local(2006, 8, 24, 12), time
time = parse_now("this month", :context => :past)
assert_equal Time.local(2006, 8, 8, 12), time
time = Chronic.parse("next month", :now => Time.local(2006, 11, 15))
assert_equal Time.local(2006, 12, 16, 12), time
# month name
time = parse_now("last november")
assert_equal Time.local(2005, 11, 16), time
# fortnight
time = parse_now("this fortnight")
assert_equal Time.local(2006, 8, 21, 19, 30), time
time = parse_now("this fortnight", :context => :past)
assert_equal Time.local(2006, 8, 14, 19), time
# week
time = parse_now("this week")
assert_equal Time.local(2006, 8, 18, 7, 30), time
time = parse_now("this week", :context => :past)
assert_equal Time.local(2006, 8, 14, 19), time
# weekend
time = parse_now("this weekend")
assert_equal Time.local(2006, 8, 20), time
time = parse_now("this weekend", :context => :past)
assert_equal Time.local(2006, 8, 13), time
time = parse_now("last weekend")
assert_equal Time.local(2006, 8, 13), time
# day
time = parse_now("this day")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("this day", :context => :past)
assert_equal Time.local(2006, 8, 16, 7), time
time = parse_now("today")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("yesterday")
assert_equal Time.local(2006, 8, 15, 12), time
now = Time.parse("2011-05-27 23:10") # after 11pm
time = parse_now("yesterday", :now => now)
assert_equal Time.local(2011, 05, 26, 12), time
time = parse_now("tomorrow")
assert_equal Time.local(2006, 8, 17, 12), time
# day name
time = parse_now("this tuesday")
assert_equal Time.local(2006, 8, 22, 12), time
time = parse_now("next tuesday")
assert_equal Time.local(2006, 8, 22, 12), time
time = parse_now("last tuesday")
assert_equal Time.local(2006, 8, 15, 12), time
time = parse_now("this wed")
assert_equal Time.local(2006, 8, 23, 12), time
time = parse_now("next wed")
assert_equal Time.local(2006, 8, 23, 12), time
time = parse_now("last wed")
assert_equal Time.local(2006, 8, 9, 12), time
# day portion
time = parse_now("this morning")
assert_equal Time.local(2006, 8, 16, 9), time
time = parse_now("tonight")
assert_equal Time.local(2006, 8, 16, 22), time
# minute
time = parse_now("next minute")
assert_equal Time.local(2006, 8, 16, 14, 1, 30), time
# second
time = parse_now("this second")
assert_equal Time.local(2006, 8, 16, 14), time
time = parse_now("this second", :context => :past)
assert_equal Time.local(2006, 8, 16, 14), time
time = parse_now("next second")
assert_equal Time.local(2006, 8, 16, 14, 0, 1), time
time = parse_now("last second")
assert_equal Time.local(2006, 8, 16, 13, 59, 59), time
end
def test_parse_guess_grr
time = parse_now("yesterday at 4:00")
assert_equal Time.local(2006, 8, 15, 16), time
time = parse_now("today at 9:00")
assert_equal Time.local(2006, 8, 16, 9), time
time = parse_now("today at 2100")
assert_equal Time.local(2006, 8, 16, 21), time
time = parse_now("this day at 0900")
assert_equal Time.local(2006, 8, 16, 9), time
time = parse_now("tomorrow at 0900")
assert_equal Time.local(2006, 8, 17, 9), time
time = parse_now("yesterday at 4:00", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 15, 4), time
time = parse_now("last friday at 4:00")
assert_equal Time.local(2006, 8, 11, 16), time
time = parse_now("next wed 4:00")
assert_equal Time.local(2006, 8, 23, 16), time
time = parse_now("yesterday afternoon")
assert_equal Time.local(2006, 8, 15, 15), time
time = parse_now("last week tuesday")
assert_equal Time.local(2006, 8, 8, 12), time
time = parse_now("tonight at 7")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("tonight 7")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("7 tonight")
assert_equal Time.local(2006, 8, 16, 19), time
end
def test_parse_guess_grrr
time = parse_now("today at 6:00pm")
assert_equal Time.local(2006, 8, 16, 18), time
time = parse_now("today at 6:00am")
assert_equal Time.local(2006, 8, 16, 6), time
time = parse_now("this day 1800")
assert_equal Time.local(2006, 8, 16, 18), time
time = parse_now("yesterday at 4:00pm")
assert_equal Time.local(2006, 8, 15, 16), time
time = parse_now("tomorrow evening at 7")
assert_equal Time.local(2006, 8, 17, 19), time
time = parse_now("tomorrow morning at 5:30")
assert_equal Time.local(2006, 8, 17, 5, 30), time
time = parse_now("next monday at 12:01 am")
assert_equal Time.local(2006, 8, 21, 00, 1), time
time = parse_now("next monday at 12:01 pm")
assert_equal Time.local(2006, 8, 21, 12, 1), time
# with context
time = parse_now("sunday at 8:15pm", :context => :past)
assert_equal Time.local(2006, 8, 13, 20, 15), time
end
def test_parse_guess_rgr
time = parse_now("afternoon yesterday")
assert_equal Time.local(2006, 8, 15, 15), time
time = parse_now("tuesday last week")
assert_equal Time.local(2006, 8, 8, 12), time
end
def test_parse_guess_s_r_p
# past
time = parse_now("3 years ago")
assert_equal Time.local(2003, 8, 16, 14), time
time = parse_now("1 month ago")
assert_equal Time.local(2006, 7, 16, 14), time
time = parse_now("1 fortnight ago")
assert_equal Time.local(2006, 8, 2, 14), time
time = parse_now("2 fortnights ago")
assert_equal Time.local(2006, 7, 19, 14), time
time = parse_now("3 weeks ago")
assert_equal Time.local(2006, 7, 26, 14), time
time = parse_now("2 weekends ago")
assert_equal Time.local(2006, 8, 5), time
time = parse_now("3 days ago")
assert_equal Time.local(2006, 8, 13, 14), time
#time = parse_now("1 monday ago")
#assert_equal Time.local(2006, 8, 14, 12), time
time = parse_now("5 mornings ago")
assert_equal Time.local(2006, 8, 12, 9), time
time = parse_now("7 hours ago")
assert_equal Time.local(2006, 8, 16, 7), time
time = parse_now("3 minutes ago")
assert_equal Time.local(2006, 8, 16, 13, 57), time
time = parse_now("20 seconds before now")
assert_equal Time.local(2006, 8, 16, 13, 59, 40), time
# future
time = parse_now("3 years from now")
assert_equal Time.local(2009, 8, 16, 14, 0, 0), time
time = parse_now("6 months hence")
assert_equal Time.local(2007, 2, 16, 14), time
time = parse_now("3 fortnights hence")
assert_equal Time.local(2006, 9, 27, 14), time
time = parse_now("1 week from now")
assert_equal Time.local(2006, 8, 23, 14, 0, 0), time
time = parse_now("1 weekend from now")
assert_equal Time.local(2006, 8, 19), time
time = parse_now("2 weekends from now")
assert_equal Time.local(2006, 8, 26), time
time = parse_now("1 day hence")
assert_equal Time.local(2006, 8, 17, 14), time
time = parse_now("5 mornings hence")
assert_equal Time.local(2006, 8, 21, 9), time
time = parse_now("1 hour from now")
assert_equal Time.local(2006, 8, 16, 15), time
time = parse_now("20 minutes hence")
assert_equal Time.local(2006, 8, 16, 14, 20), time
time = parse_now("20 seconds from now")
assert_equal Time.local(2006, 8, 16, 14, 0, 20), time
time = Chronic.parse("2 months ago", :now => Time.parse("2007-03-07 23:30"))
assert_equal Time.local(2007, 1, 7, 23, 30), time
end
def test_parse_guess_p_s_r
time = parse_now("in 3 hours")
assert_equal Time.local(2006, 8, 16, 17), time
end
def test_parse_guess_s_r_p_a
# past
time = parse_now("3 years ago tomorrow")
assert_equal Time.local(2003, 8, 17, 12), time
time = parse_now("3 years ago this friday")
assert_equal Time.local(2003, 8, 18, 12), time
time = parse_now("3 months ago saturday at 5:00 pm")
assert_equal Time.local(2006, 5, 19, 17), time
time = parse_now("2 days from this second")
assert_equal Time.local(2006, 8, 18, 14), time
time = parse_now("7 hours before tomorrow at midnight")
assert_equal Time.local(2006, 8, 17, 17), time
# future
end
def test_parse_guess_o_r_g_r
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3), time.begin
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3, 1), time.begin
time = parse_now("3rd thursday this september")
assert_equal Time.local(2006, 9, 21, 12), time
now = Time.parse("1/10/2010")
time = parse_now("3rd thursday this november", :now => now)
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("4th day last week")
assert_equal Time.local(2006, 8, 9, 12), time
end
def test_parse_guess_nonsense
time = parse_now("some stupid nonsense")
assert_equal nil, time
time = parse_now("Ham Sandwich")
assert_equal nil, time
end
def test_parse_span
span = parse_now("friday", :guess => false)
assert_equal Time.local(2006, 8, 18), span.begin
assert_equal Time.local(2006, 8, 19), span.end
span = parse_now("november", :guess => false)
assert_equal Time.local(2006, 11), span.begin
assert_equal Time.local(2006, 12), span.end
span = Chronic.parse("weekend" , :now => @time_2006_08_16_14_00_00, :guess => false)
assert_equal Time.local(2006, 8, 19), span.begin
assert_equal Time.local(2006, 8, 21), span.end
end
def test_parse_with_endian_precedence
date = '11/02/2007'
expect_for_middle_endian = Time.local(2007, 11, 2, 12)
expect_for_little_endian = Time.local(2007, 2, 11, 12)
# default precedence should be toward middle endianness
assert_equal expect_for_middle_endian, Chronic.parse(date)
assert_equal expect_for_middle_endian, Chronic.parse(date, :endian_precedence => [:middle, :little])
assert_equal expect_for_little_endian, Chronic.parse(date, :endian_precedence => [:little, :middle])
end
def test_parse_words
assert_equal parse_now("33 days from now"), parse_now("thirty-three days from now")
assert_equal parse_now("2867532 seconds from now"), parse_now("two million eight hundred and sixty seven thousand five hundred and thirty two seconds from now")
assert_equal parse_now("may 10th"), parse_now("may tenth")
end
def test_parse_only_complete_pointers
assert_equal parse_now("eat pasty buns today at 2pm"), @time_2006_08_16_14_00_00
assert_equal parse_now("futuristically speaking today at 2pm"), @time_2006_08_16_14_00_00
assert_equal parse_now("meeting today at 2pm"), @time_2006_08_16_14_00_00
end
def test_am_pm
assert_equal Time.local(2006, 8, 16), parse_now("8/16/2006 at 12am")
assert_equal Time.local(2006, 8, 16, 12), parse_now("8/16/2006 at 12pm")
end
def test_a_p
assert_equal Time.local(2006, 8, 16, 0, 15), parse_now("8/16/2006 at 12:15a")
assert_equal Time.local(2006, 8, 16, 18, 30), parse_now("8/16/2006 at 6:30p")
end
def test_argument_validation
assert_raise(ArgumentError) do
time = Chronic.parse("may 27", :foo => :bar)
end
assert_raise(ArgumentError) do
time = Chronic.parse("may 27", :context => :bar)
end
end
def test_seasons
t = parse_now("this spring", :guess => false)
assert_equal Time.local(2007, 3, 20), t.begin
assert_equal Time.local(2007, 6, 20), t.end
t = parse_now("this winter", :guess => false)
assert_equal Time.local(2006, 12, 22), t.begin
assert_equal Time.local(2007, 3, 19), t.end
t = parse_now("last spring", :guess => false)
assert_equal Time.local(2006, 3, 20), t.begin
assert_equal Time.local(2006, 6, 20), t.end
t = parse_now("last winter", :guess => false)
assert_equal Time.local(2005, 12, 22), t.begin
assert_equal Time.local(2006, 3, 19), t.end
t = parse_now("next spring", :guess => false)
assert_equal Time.local(2007, 3, 20), t.begin
assert_equal Time.local(2007, 6, 20), t.end
end
# regression
# def test_partial
# assert_equal '', parse_now("2 hours")
# end
def test_days_in_november
t1 = Chronic.parse('1st thursday in november', :now => Time.local(2007))
assert_equal Time.local(2007, 11, 1, 12), t1
t1 = Chronic.parse('1st friday in november', :now => Time.local(2007))
assert_equal Time.local(2007, 11, 2, 12), t1
t1 = Chronic.parse('1st saturday in november', :now => Time.local(2007))
assert_equal Time.local(2007, 11, 3, 12), t1
# t1 = Chronic.parse('1st sunday in november', :now => Time.local(2007))
# assert_equal Time.local(2007, 11, 4, 12), t1
# Chronic.debug = true
#
# t1 = Chronic.parse('1st monday in november', :now => Time.local(2007))
# assert_equal Time.local(2007, 11, 5, 11), t1
end
def test_now_changes
t1 = Chronic.parse("now")
sleep 0.1
t2 = Chronic.parse("now")
assert_not_equal t1, t2
end
def test_noon
t1 = Chronic.parse('2011-01-01 at noon', :ambiguous_time_range => :none)
assert_equal Time.local(2011, 1, 1, 12, 0), t1
end
def test_handle_rdn_rmn_sd
time = parse_now("Thu Aug 10")
assert_equal Time.local(2006, 8, 10, 12), time
end
def test_handle_rdn_rmn_od
time = parse_now("Thu Aug 10th")
assert_equal Time.local(2006, 8, 10, 12), time
end
private
def parse_now(string, options={})
Chronic.parse(string, {:now => TIME_2006_08_16_14_00_00 }.merge(options))
end
end
added more extensive tests for orr handling
require 'helper'
class TestParsing < Test::Unit::TestCase
# Wed Aug 16 14:00:00 UTC 2006
TIME_2006_08_16_14_00_00 = Time.local(2006, 8, 16, 14, 0, 0, 0)
def setup
@time_2006_08_16_14_00_00 = TIME_2006_08_16_14_00_00
end
def test_handle_rmn_sd
time = parse_now("aug 3")
assert_equal Time.local(2006, 8, 3, 12), time
time = parse_now("aug 3", :context => :past)
assert_equal Time.local(2006, 8, 3, 12), time
time = parse_now("aug 20")
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("aug 20", :context => :future)
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("may 27")
assert_equal Time.local(2007, 5, 27, 12), time
time = parse_now("may 28", :context => :past)
assert_equal Time.local(2006, 5, 28, 12), time
time = parse_now("may 28 5pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17), time
time = parse_now("may 28 at 5pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17), time
time = parse_now("may 28 at 5:32.19pm", :context => :past)
assert_equal Time.local(2006, 5, 28, 17, 32, 19), time
end
def test_handle_rmn_sd_on
time = parse_now("5pm on may 28")
assert_equal Time.local(2007, 5, 28, 17), time
time = parse_now("5pm may 28")
assert_equal Time.local(2007, 5, 28, 17), time
time = parse_now("5 on may 28", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 28, 05), time
end
def test_handle_rmn_od
time = parse_now("may 27th")
assert_equal Time.local(2007, 5, 27, 12), time
time = parse_now("may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 12), time
time = parse_now("may 27th 5:00 pm", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("may 27th at 5pm", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("may 27th at 5", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 27, 5), time
end
def test_handle_od_rmn
time = parse_now("22nd February")
assert_equal Time.local(2007, 2, 22, 12), time
time = parse_now("31st of may at 6:30pm")
assert_equal Time.local(2007, 5, 31, 18, 30), time
time = parse_now("11th december 8am")
assert_equal Time.local(2006, 12, 11, 8), time
end
def test_handle_sy_rmn_od
time = parse_now("2009 May 22nd")
assert_equal Time.local(2009, 05, 22, 12), time
end
def test_handle_sd_rmn
time = parse_now("22 February")
assert_equal Time.local(2007, 2, 22, 12), time
time = parse_now("31 of may at 6:30pm")
assert_equal Time.local(2007, 5, 31, 18, 30), time
time = parse_now("11 december 8am")
assert_equal Time.local(2006, 12, 11, 8), time
end
def test_handle_rmn_od_on
time = parse_now("5:00 pm may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("05:00 pm may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("5pm on may 27th", :context => :past)
assert_equal Time.local(2006, 5, 27, 17), time
time = parse_now("5 on may 27th", :ambiguous_time_range => :none)
assert_equal Time.local(2007, 5, 27, 5), time
end
def test_handle_rmn_sy
time = parse_now("may 97")
assert_equal Time.local(1997, 5, 16, 12), time
time = parse_now("may 33", :ambiguous_year_future_bias => 10)
assert_equal Time.local(2033, 5, 16, 12), time
time = parse_now("may 32")
assert_equal Time.local(2032, 5, 16, 12, 0, 0), time
end
def test_handle_rdn_rmn_sd_t_tz_sy
time = parse_now("Mon Apr 02 17:00:00 PDT 2007")
assert_equal 1175558400, time.to_i
end
def test_handle_sy_sm_sd_t_tz
time = parse_now("2011-07-03 22:11:35 +0100")
assert_equal 1309727495, time.to_i
time = parse_now("2011-07-03 22:11:35 +01:00")
assert_equal 1309727495, time.to_i
time = parse_now("2011-07-03 21:11:35 UTC")
assert_equal 1309727495, time.to_i
end
def test_handle_rmn_sd_sy
time = parse_now("November 18, 2010")
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("Jan 1,2010")
assert_equal Time.local(2010, 1, 1, 12), time
time = parse_now("February 14, 2004")
assert_equal Time.local(2004, 2, 14, 12), time
time = parse_now("jan 3 2010")
assert_equal Time.local(2010, 1, 3, 12), time
time = parse_now("jan 3 2010 midnight")
assert_equal Time.local(2010, 1, 4, 0), time
time = parse_now("jan 3 2010 at midnight")
assert_equal Time.local(2010, 1, 4, 0), time
time = parse_now("jan 3 2010 at 4", :ambiguous_time_range => :none)
assert_equal Time.local(2010, 1, 3, 4), time
time = parse_now("may 27, 1979")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("may 27 79")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("may 27 79 4:30")
assert_equal Time.local(1979, 5, 27, 16, 30), time
time = parse_now("may 27 79 at 4:30", :ambiguous_time_range => :none)
assert_equal Time.local(1979, 5, 27, 4, 30), time
time = parse_now("may 27 32")
assert_equal Time.local(2032, 5, 27, 12, 0, 0), time
end
def test_handle_rmn_od_sy
time = parse_now("may 1st 01")
assert_equal Time.local(2001, 5, 1, 12), time
time = parse_now("November 18th 2010")
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("November 18th, 2010")
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("November 18th 2010 midnight")
assert_equal Time.local(2010, 11, 19, 0), time
time = parse_now("November 18th 2010 at midnight")
assert_equal Time.local(2010, 11, 19, 0), time
time = parse_now("November 18th 2010 at 4")
assert_equal Time.local(2010, 11, 18, 16), time
time = parse_now("November 18th 2010 at 4", :ambiguous_time_range => :none)
assert_equal Time.local(2010, 11, 18, 4), time
time = parse_now("March 30th, 1979")
assert_equal Time.local(1979, 3, 30, 12), time
time = parse_now("March 30th 79")
assert_equal Time.local(1979, 3, 30, 12), time
time = parse_now("March 30th 79 4:30")
assert_equal Time.local(1979, 3, 30, 16, 30), time
time = parse_now("March 30th 79 at 4:30", :ambiguous_time_range => :none)
assert_equal Time.local(1979, 3, 30, 4, 30), time
end
def test_handle_od_rmn_sy
time = parse_now("22nd February 2012")
assert_equal Time.local(2012, 2, 22, 12), time
time = parse_now("11th december 79")
assert_equal Time.local(1979, 12, 11, 12), time
end
def test_handle_sd_rmn_sy
time = parse_now("3 jan 2010")
assert_equal Time.local(2010, 1, 3, 12), time
time = parse_now("3 jan 2010 4pm")
assert_equal Time.local(2010, 1, 3, 16), time
time = parse_now("27 Oct 2006 7:30pm")
assert_equal Time.local(2006, 10, 27, 19, 30), time
end
def test_handle_sm_sd_sy
time = parse_now("5/27/1979")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("5/27/1979 4am")
assert_equal Time.local(1979, 5, 27, 4), time
time = parse_now("7/12/11")
assert_equal Time.local(2011, 7, 12, 12), time
time = parse_now("7/12/11", :endian_precedence => :little)
assert_equal Time.local(2011, 12, 7, 12), time
time = parse_now("9/19/2011 6:05:57 PM")
assert_equal Time.local(2011, 9, 19, 18, 05, 57), time
# month day overflows
time = parse_now("30/2/2000")
assert_nil time
end
def test_handle_sd_sm_sy
time = parse_now("27/5/1979")
assert_equal Time.local(1979, 5, 27, 12), time
time = parse_now("27/5/1979 @ 0700")
assert_equal Time.local(1979, 5, 27, 7), time
end
def test_handle_sy_sm_sd
time = parse_now("2000-1-1")
assert_equal Time.local(2000, 1, 1, 12), time
time = parse_now("2006-08-20")
assert_equal Time.local(2006, 8, 20, 12), time
time = parse_now("2006-08-20 7pm")
assert_equal Time.local(2006, 8, 20, 19), time
time = parse_now("2006-08-20 03:00")
assert_equal Time.local(2006, 8, 20, 3), time
time = parse_now("2006-08-20 03:30:30")
assert_equal Time.local(2006, 8, 20, 3, 30, 30), time
time = parse_now("2006-08-20 15:30:30")
assert_equal Time.local(2006, 8, 20, 15, 30, 30), time
time = parse_now("2006-08-20 15:30.30")
assert_equal Time.local(2006, 8, 20, 15, 30, 30), time
time = parse_now("1902-08-20")
assert_equal Time.local(1902, 8, 20, 12, 0, 0), time
end
def test_handle_sm_sy
time = parse_now("05/06")
assert_equal Time.local(2006, 5, 16, 12), time
time = parse_now("12/06")
assert_equal Time.local(2006, 12, 16, 12), time
time = parse_now("13/06")
assert_equal nil, time
end
def test_handle_r
end
def test_handle_r_g_r
end
def test_handle_srp
end
def test_handle_s_r_p
end
def test_handle_p_s_r
end
def test_handle_s_r_p_a
end
def test_handle_orr
time = parse_now("5th tuesday in january")
assert_equal Time.local(2007, 01, 30, 12), time
time = parse_now("5th tuesday in february")
assert_equal nil, time
%W(jan feb march april may june july aug sep oct nov dec).each_with_index do |month, index|
time = parse_now("5th tuesday in #{month}")
if time then
assert_equal time.month, index+1
end
end
end
def test_handle_o_r_s_r
time = parse_now("3rd wednesday in november")
assert_equal Time.local(2006, 11, 15, 12), time
time = parse_now("10th wednesday in november")
assert_equal nil, time
# time = parse_now("3rd wednesday in 2007")
# assert_equal Time.local(2007, 1, 20, 12), time
end
def test_handle_o_r_g_r
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3), time.begin
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3, 1), time.begin
time = parse_now("3rd thursday this september")
assert_equal Time.local(2006, 9, 21, 12), time
now = Time.parse("1/10/2010")
time = parse_now("3rd thursday this november", :now => now)
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("4th day last week")
assert_equal Time.local(2006, 8, 9, 12), time
end
# end of testing handlers
def test_parse_guess_r
time = parse_now("friday")
assert_equal Time.local(2006, 8, 18, 12), time
time = parse_now("tue")
assert_equal Time.local(2006, 8, 22, 12), time
time = parse_now("5")
assert_equal Time.local(2006, 8, 16, 17), time
time = Chronic.parse("5", :now => Time.local(2006, 8, 16, 3, 0, 0, 0), :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 16, 5), time
time = parse_now("13:00")
assert_equal Time.local(2006, 8, 17, 13), time
time = parse_now("13:45")
assert_equal Time.local(2006, 8, 17, 13, 45), time
time = parse_now("1:01pm")
assert_equal Time.local(2006, 8, 16, 13, 01), time
time = parse_now("2:01pm")
assert_equal Time.local(2006, 8, 16, 14, 01), time
time = parse_now("november")
assert_equal Time.local(2006, 11, 16), time
end
def test_parse_guess_rr
time = parse_now("friday 13:00")
assert_equal Time.local(2006, 8, 18, 13), time
time = parse_now("monday 4:00")
assert_equal Time.local(2006, 8, 21, 16), time
time = parse_now("sat 4:00", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 19, 4), time
time = parse_now("sunday 4:20", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 20, 4, 20), time
time = parse_now("4 pm")
assert_equal Time.local(2006, 8, 16, 16), time
time = parse_now("4 am", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 16, 4), time
time = parse_now("12 pm")
assert_equal Time.local(2006, 8, 16, 12), time
time = parse_now("12:01 pm")
assert_equal Time.local(2006, 8, 16, 12, 1), time
time = parse_now("12:01 am")
assert_equal Time.local(2006, 8, 16, 0, 1), time
time = parse_now("12 am")
assert_equal Time.local(2006, 8, 16), time
time = parse_now("4:00 in the morning")
assert_equal Time.local(2006, 8, 16, 4), time
time = parse_now("0:10")
assert_equal Time.local(2006, 8, 17, 0, 10), time
time = parse_now("november 4")
assert_equal Time.local(2006, 11, 4, 12), time
time = parse_now("aug 24")
assert_equal Time.local(2006, 8, 24, 12), time
end
def test_parse_guess_rrr
time = parse_now("friday 1 pm")
assert_equal Time.local(2006, 8, 18, 13), time
time = parse_now("friday 11 at night")
assert_equal Time.local(2006, 8, 18, 23), time
time = parse_now("friday 11 in the evening")
assert_equal Time.local(2006, 8, 18, 23), time
time = parse_now("sunday 6am")
assert_equal Time.local(2006, 8, 20, 6), time
time = parse_now("friday evening at 7")
assert_equal Time.local(2006, 8, 18, 19), time
end
def test_parse_guess_gr
# year
time = parse_now("this year", :guess => false)
assert_equal Time.local(2006, 8, 17), time.begin
time = parse_now("this year", :context => :past, :guess => false)
assert_equal Time.local(2006, 1, 1), time.begin
# month
time = parse_now("this month")
assert_equal Time.local(2006, 8, 24, 12), time
time = parse_now("this month", :context => :past)
assert_equal Time.local(2006, 8, 8, 12), time
time = Chronic.parse("next month", :now => Time.local(2006, 11, 15))
assert_equal Time.local(2006, 12, 16, 12), time
# month name
time = parse_now("last november")
assert_equal Time.local(2005, 11, 16), time
# fortnight
time = parse_now("this fortnight")
assert_equal Time.local(2006, 8, 21, 19, 30), time
time = parse_now("this fortnight", :context => :past)
assert_equal Time.local(2006, 8, 14, 19), time
# week
time = parse_now("this week")
assert_equal Time.local(2006, 8, 18, 7, 30), time
time = parse_now("this week", :context => :past)
assert_equal Time.local(2006, 8, 14, 19), time
# weekend
time = parse_now("this weekend")
assert_equal Time.local(2006, 8, 20), time
time = parse_now("this weekend", :context => :past)
assert_equal Time.local(2006, 8, 13), time
time = parse_now("last weekend")
assert_equal Time.local(2006, 8, 13), time
# day
time = parse_now("this day")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("this day", :context => :past)
assert_equal Time.local(2006, 8, 16, 7), time
time = parse_now("today")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("yesterday")
assert_equal Time.local(2006, 8, 15, 12), time
now = Time.parse("2011-05-27 23:10") # after 11pm
time = parse_now("yesterday", :now => now)
assert_equal Time.local(2011, 05, 26, 12), time
time = parse_now("tomorrow")
assert_equal Time.local(2006, 8, 17, 12), time
# day name
time = parse_now("this tuesday")
assert_equal Time.local(2006, 8, 22, 12), time
time = parse_now("next tuesday")
assert_equal Time.local(2006, 8, 22, 12), time
time = parse_now("last tuesday")
assert_equal Time.local(2006, 8, 15, 12), time
time = parse_now("this wed")
assert_equal Time.local(2006, 8, 23, 12), time
time = parse_now("next wed")
assert_equal Time.local(2006, 8, 23, 12), time
time = parse_now("last wed")
assert_equal Time.local(2006, 8, 9, 12), time
# day portion
time = parse_now("this morning")
assert_equal Time.local(2006, 8, 16, 9), time
time = parse_now("tonight")
assert_equal Time.local(2006, 8, 16, 22), time
# minute
time = parse_now("next minute")
assert_equal Time.local(2006, 8, 16, 14, 1, 30), time
# second
time = parse_now("this second")
assert_equal Time.local(2006, 8, 16, 14), time
time = parse_now("this second", :context => :past)
assert_equal Time.local(2006, 8, 16, 14), time
time = parse_now("next second")
assert_equal Time.local(2006, 8, 16, 14, 0, 1), time
time = parse_now("last second")
assert_equal Time.local(2006, 8, 16, 13, 59, 59), time
end
def test_parse_guess_grr
time = parse_now("yesterday at 4:00")
assert_equal Time.local(2006, 8, 15, 16), time
time = parse_now("today at 9:00")
assert_equal Time.local(2006, 8, 16, 9), time
time = parse_now("today at 2100")
assert_equal Time.local(2006, 8, 16, 21), time
time = parse_now("this day at 0900")
assert_equal Time.local(2006, 8, 16, 9), time
time = parse_now("tomorrow at 0900")
assert_equal Time.local(2006, 8, 17, 9), time
time = parse_now("yesterday at 4:00", :ambiguous_time_range => :none)
assert_equal Time.local(2006, 8, 15, 4), time
time = parse_now("last friday at 4:00")
assert_equal Time.local(2006, 8, 11, 16), time
time = parse_now("next wed 4:00")
assert_equal Time.local(2006, 8, 23, 16), time
time = parse_now("yesterday afternoon")
assert_equal Time.local(2006, 8, 15, 15), time
time = parse_now("last week tuesday")
assert_equal Time.local(2006, 8, 8, 12), time
time = parse_now("tonight at 7")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("tonight 7")
assert_equal Time.local(2006, 8, 16, 19), time
time = parse_now("7 tonight")
assert_equal Time.local(2006, 8, 16, 19), time
end
def test_parse_guess_grrr
time = parse_now("today at 6:00pm")
assert_equal Time.local(2006, 8, 16, 18), time
time = parse_now("today at 6:00am")
assert_equal Time.local(2006, 8, 16, 6), time
time = parse_now("this day 1800")
assert_equal Time.local(2006, 8, 16, 18), time
time = parse_now("yesterday at 4:00pm")
assert_equal Time.local(2006, 8, 15, 16), time
time = parse_now("tomorrow evening at 7")
assert_equal Time.local(2006, 8, 17, 19), time
time = parse_now("tomorrow morning at 5:30")
assert_equal Time.local(2006, 8, 17, 5, 30), time
time = parse_now("next monday at 12:01 am")
assert_equal Time.local(2006, 8, 21, 00, 1), time
time = parse_now("next monday at 12:01 pm")
assert_equal Time.local(2006, 8, 21, 12, 1), time
# with context
time = parse_now("sunday at 8:15pm", :context => :past)
assert_equal Time.local(2006, 8, 13, 20, 15), time
end
def test_parse_guess_rgr
time = parse_now("afternoon yesterday")
assert_equal Time.local(2006, 8, 15, 15), time
time = parse_now("tuesday last week")
assert_equal Time.local(2006, 8, 8, 12), time
end
def test_parse_guess_s_r_p
# past
time = parse_now("3 years ago")
assert_equal Time.local(2003, 8, 16, 14), time
time = parse_now("1 month ago")
assert_equal Time.local(2006, 7, 16, 14), time
time = parse_now("1 fortnight ago")
assert_equal Time.local(2006, 8, 2, 14), time
time = parse_now("2 fortnights ago")
assert_equal Time.local(2006, 7, 19, 14), time
time = parse_now("3 weeks ago")
assert_equal Time.local(2006, 7, 26, 14), time
time = parse_now("2 weekends ago")
assert_equal Time.local(2006, 8, 5), time
time = parse_now("3 days ago")
assert_equal Time.local(2006, 8, 13, 14), time
#time = parse_now("1 monday ago")
#assert_equal Time.local(2006, 8, 14, 12), time
time = parse_now("5 mornings ago")
assert_equal Time.local(2006, 8, 12, 9), time
time = parse_now("7 hours ago")
assert_equal Time.local(2006, 8, 16, 7), time
time = parse_now("3 minutes ago")
assert_equal Time.local(2006, 8, 16, 13, 57), time
time = parse_now("20 seconds before now")
assert_equal Time.local(2006, 8, 16, 13, 59, 40), time
# future
time = parse_now("3 years from now")
assert_equal Time.local(2009, 8, 16, 14, 0, 0), time
time = parse_now("6 months hence")
assert_equal Time.local(2007, 2, 16, 14), time
time = parse_now("3 fortnights hence")
assert_equal Time.local(2006, 9, 27, 14), time
time = parse_now("1 week from now")
assert_equal Time.local(2006, 8, 23, 14, 0, 0), time
time = parse_now("1 weekend from now")
assert_equal Time.local(2006, 8, 19), time
time = parse_now("2 weekends from now")
assert_equal Time.local(2006, 8, 26), time
time = parse_now("1 day hence")
assert_equal Time.local(2006, 8, 17, 14), time
time = parse_now("5 mornings hence")
assert_equal Time.local(2006, 8, 21, 9), time
time = parse_now("1 hour from now")
assert_equal Time.local(2006, 8, 16, 15), time
time = parse_now("20 minutes hence")
assert_equal Time.local(2006, 8, 16, 14, 20), time
time = parse_now("20 seconds from now")
assert_equal Time.local(2006, 8, 16, 14, 0, 20), time
time = Chronic.parse("2 months ago", :now => Time.parse("2007-03-07 23:30"))
assert_equal Time.local(2007, 1, 7, 23, 30), time
end
def test_parse_guess_p_s_r
time = parse_now("in 3 hours")
assert_equal Time.local(2006, 8, 16, 17), time
end
def test_parse_guess_s_r_p_a
# past
time = parse_now("3 years ago tomorrow")
assert_equal Time.local(2003, 8, 17, 12), time
time = parse_now("3 years ago this friday")
assert_equal Time.local(2003, 8, 18, 12), time
time = parse_now("3 months ago saturday at 5:00 pm")
assert_equal Time.local(2006, 5, 19, 17), time
time = parse_now("2 days from this second")
assert_equal Time.local(2006, 8, 18, 14), time
time = parse_now("7 hours before tomorrow at midnight")
assert_equal Time.local(2006, 8, 17, 17), time
# future
end
def test_parse_guess_o_r_g_r
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3), time.begin
time = parse_now("3rd month next year", :guess => false)
assert_equal Time.local(2007, 3, 1), time.begin
time = parse_now("3rd thursday this september")
assert_equal Time.local(2006, 9, 21, 12), time
now = Time.parse("1/10/2010")
time = parse_now("3rd thursday this november", :now => now)
assert_equal Time.local(2010, 11, 18, 12), time
time = parse_now("4th day last week")
assert_equal Time.local(2006, 8, 9, 12), time
end
def test_parse_guess_nonsense
time = parse_now("some stupid nonsense")
assert_equal nil, time
time = parse_now("Ham Sandwich")
assert_equal nil, time
end
def test_parse_span
span = parse_now("friday", :guess => false)
assert_equal Time.local(2006, 8, 18), span.begin
assert_equal Time.local(2006, 8, 19), span.end
span = parse_now("november", :guess => false)
assert_equal Time.local(2006, 11), span.begin
assert_equal Time.local(2006, 12), span.end
span = Chronic.parse("weekend" , :now => @time_2006_08_16_14_00_00, :guess => false)
assert_equal Time.local(2006, 8, 19), span.begin
assert_equal Time.local(2006, 8, 21), span.end
end
def test_parse_with_endian_precedence
date = '11/02/2007'
expect_for_middle_endian = Time.local(2007, 11, 2, 12)
expect_for_little_endian = Time.local(2007, 2, 11, 12)
# default precedence should be toward middle endianness
assert_equal expect_for_middle_endian, Chronic.parse(date)
assert_equal expect_for_middle_endian, Chronic.parse(date, :endian_precedence => [:middle, :little])
assert_equal expect_for_little_endian, Chronic.parse(date, :endian_precedence => [:little, :middle])
end
def test_parse_words
assert_equal parse_now("33 days from now"), parse_now("thirty-three days from now")
assert_equal parse_now("2867532 seconds from now"), parse_now("two million eight hundred and sixty seven thousand five hundred and thirty two seconds from now")
assert_equal parse_now("may 10th"), parse_now("may tenth")
end
def test_parse_only_complete_pointers
assert_equal parse_now("eat pasty buns today at 2pm"), @time_2006_08_16_14_00_00
assert_equal parse_now("futuristically speaking today at 2pm"), @time_2006_08_16_14_00_00
assert_equal parse_now("meeting today at 2pm"), @time_2006_08_16_14_00_00
end
def test_am_pm
assert_equal Time.local(2006, 8, 16), parse_now("8/16/2006 at 12am")
assert_equal Time.local(2006, 8, 16, 12), parse_now("8/16/2006 at 12pm")
end
def test_a_p
assert_equal Time.local(2006, 8, 16, 0, 15), parse_now("8/16/2006 at 12:15a")
assert_equal Time.local(2006, 8, 16, 18, 30), parse_now("8/16/2006 at 6:30p")
end
def test_argument_validation
assert_raise(ArgumentError) do
time = Chronic.parse("may 27", :foo => :bar)
end
assert_raise(ArgumentError) do
time = Chronic.parse("may 27", :context => :bar)
end
end
def test_seasons
t = parse_now("this spring", :guess => false)
assert_equal Time.local(2007, 3, 20), t.begin
assert_equal Time.local(2007, 6, 20), t.end
t = parse_now("this winter", :guess => false)
assert_equal Time.local(2006, 12, 22), t.begin
assert_equal Time.local(2007, 3, 19), t.end
t = parse_now("last spring", :guess => false)
assert_equal Time.local(2006, 3, 20), t.begin
assert_equal Time.local(2006, 6, 20), t.end
t = parse_now("last winter", :guess => false)
assert_equal Time.local(2005, 12, 22), t.begin
assert_equal Time.local(2006, 3, 19), t.end
t = parse_now("next spring", :guess => false)
assert_equal Time.local(2007, 3, 20), t.begin
assert_equal Time.local(2007, 6, 20), t.end
end
# regression
# def test_partial
# assert_equal '', parse_now("2 hours")
# end
def test_days_in_november
t1 = Chronic.parse('1st thursday in november', :now => Time.local(2007))
assert_equal Time.local(2007, 11, 1, 12), t1
t1 = Chronic.parse('1st friday in november', :now => Time.local(2007))
assert_equal Time.local(2007, 11, 2, 12), t1
t1 = Chronic.parse('1st saturday in november', :now => Time.local(2007))
assert_equal Time.local(2007, 11, 3, 12), t1
# t1 = Chronic.parse('1st sunday in november', :now => Time.local(2007))
# assert_equal Time.local(2007, 11, 4, 12), t1
# Chronic.debug = true
#
# t1 = Chronic.parse('1st monday in november', :now => Time.local(2007))
# assert_equal Time.local(2007, 11, 5, 11), t1
end
def test_now_changes
t1 = Chronic.parse("now")
sleep 0.1
t2 = Chronic.parse("now")
assert_not_equal t1, t2
end
def test_noon
t1 = Chronic.parse('2011-01-01 at noon', :ambiguous_time_range => :none)
assert_equal Time.local(2011, 1, 1, 12, 0), t1
end
def test_handle_rdn_rmn_sd
time = parse_now("Thu Aug 10")
assert_equal Time.local(2006, 8, 10, 12), time
end
def test_handle_rdn_rmn_od
time = parse_now("Thu Aug 10th")
assert_equal Time.local(2006, 8, 10, 12), time
end
private
def parse_now(string, options={})
Chronic.parse(string, {:now => TIME_2006_08_16_14_00_00 }.merge(options))
end
end
|
module GeokitRails
VERSION = "2.0.1"
end
Bump version
module GeokitRails
VERSION = "2.1.0"
end
|
module GhostWriter
VERSION = "0.4.1"
end
Bump up version to v0.4.2 [ci skip]
module GhostWriter
VERSION = "0.4.2"
end
|
# frozen_string_literal: true
module GitHubPages
# Manages the constants the govern what plugins are allows on GitHub Pages
class Plugins
# Plugins which are activated by default
DEFAULT_PLUGINS = %w(
jekyll-coffeescript
jekyll-commonmark-ghpages
jekyll-gist
jekyll-github-metadata
jekyll-paginate
jekyll-relative-links
jekyll-optional-front-matter
jekyll-readme-index
jekyll-default-layout
jekyll-titles-from-headings
).freeze
# Plugins allowed by GitHub Pages
PLUGIN_WHITELIST = %w(
jekyll-coffeescript
jekyll-commonmark-ghpages
jekyll-feed
jekyll-gist
jekyll-github-metadata
jekyll-paginate
jekyll-redirect-from
jekyll-seo-tag
jekyll-sitemap
jekyll-avatar
jemoji
jekyll-mentions
jekyll-relative-links
jekyll-optional-front-matter
jekyll-readme-index
jekyll-default-layout
jekyll-titles-from-headings
jekyll-include-cache
jekyll-octicons
jekyll-remote-theme
).freeze
# Plugins only allowed locally
DEVELOPMENT_PLUGINS = %w(
jekyll-admin
).freeze
# Themes
THEMES = {
"minima" => "2.1.1",
"jekyll-swiss" => "0.4.0",
"jekyll-theme-primer" => "0.5.2",
"jekyll-theme-architect" => "0.1.0",
"jekyll-theme-cayman" => "0.1.0",
"jekyll-theme-dinky" => "0.1.0",
"jekyll-theme-hacker" => "0.1.0",
"jekyll-theme-leap-day" => "0.1.0",
"jekyll-theme-merlot" => "0.1.0",
"jekyll-theme-midnight" => "0.1.0",
"jekyll-theme-minimal" => "0.1.0",
"jekyll-theme-modernist" => "0.1.0",
"jekyll-theme-slate" => "0.1.0",
"jekyll-theme-tactile" => "0.1.0",
"jekyll-theme-time-machine" => "0.1.0",
}.freeze
end
end
Update minima theme to 2.4.0
Signed-off-by: Antonio Gutierrez <2f780b53bb047ab4c7f7bb5d6f625a6871055abe@gmail.com>
# frozen_string_literal: true
module GitHubPages
# Manages the constants the govern what plugins are allows on GitHub Pages
class Plugins
# Plugins which are activated by default
DEFAULT_PLUGINS = %w(
jekyll-coffeescript
jekyll-commonmark-ghpages
jekyll-gist
jekyll-github-metadata
jekyll-paginate
jekyll-relative-links
jekyll-optional-front-matter
jekyll-readme-index
jekyll-default-layout
jekyll-titles-from-headings
).freeze
# Plugins allowed by GitHub Pages
PLUGIN_WHITELIST = %w(
jekyll-coffeescript
jekyll-commonmark-ghpages
jekyll-feed
jekyll-gist
jekyll-github-metadata
jekyll-paginate
jekyll-redirect-from
jekyll-seo-tag
jekyll-sitemap
jekyll-avatar
jemoji
jekyll-mentions
jekyll-relative-links
jekyll-optional-front-matter
jekyll-readme-index
jekyll-default-layout
jekyll-titles-from-headings
jekyll-include-cache
jekyll-octicons
jekyll-remote-theme
).freeze
# Plugins only allowed locally
DEVELOPMENT_PLUGINS = %w(
jekyll-admin
).freeze
# Themes
THEMES = {
"minima" => "2.4.0",
"jekyll-swiss" => "0.4.0",
"jekyll-theme-primer" => "0.5.2",
"jekyll-theme-architect" => "0.1.0",
"jekyll-theme-cayman" => "0.1.0",
"jekyll-theme-dinky" => "0.1.0",
"jekyll-theme-hacker" => "0.1.0",
"jekyll-theme-leap-day" => "0.1.0",
"jekyll-theme-merlot" => "0.1.0",
"jekyll-theme-midnight" => "0.1.0",
"jekyll-theme-minimal" => "0.1.0",
"jekyll-theme-modernist" => "0.1.0",
"jekyll-theme-slate" => "0.1.0",
"jekyll-theme-tactile" => "0.1.0",
"jekyll-theme-time-machine" => "0.1.0",
}.freeze
end
end
|
require 'net/http'
require 'json'
require 'cgi'
module Build
module Trigger
def invoke!(image: nil)
uri = URI("https://gitlab.com/api/v4/projects/#{CGI.escape(get_project_path)}/trigger/pipeline")
params = get_params(image: image)
res = Net::HTTP.post_form(uri, params)
id = JSON.parse(res.body)['id']
raise "Trigger failed! The response from the trigger is: #{res.body}" unless id
puts "Triggered https://gitlab.com/#{get_project_path}/pipelines/#{id}"
puts "Waiting for downstream pipeline status"
Build::Trigger::Pipeline.new(id, get_project_path, get_access_token)
end
class Pipeline
INTERVAL = 60 # seconds
MAX_DURATION = 3600 * 3 # 3 hours
def initialize(id, project_path, access_token)
@start = Time.now.to_i
@access_token = access_token
@uri = URI("https://gitlab.com/api/v4/projects/#{CGI.escape(project_path)}/pipelines/#{id}")
end
def wait!
loop do
raise "Pipeline timed out after waiting for #{duration} minutes!" if timeout?
case status
when :created, :pending, :running
print "."
sleep INTERVAL
when :success
puts "Pipeline succeeded in #{duration} minutes!"
break
else
raise "Pipeline did not succeed!"
end
STDOUT.flush
end
end
def timeout?
Time.now.to_i > (@start + MAX_DURATION)
end
def duration
(Time.now.to_i - @start) / 60
end
def status
req = Net::HTTP::Get.new(@uri)
req['PRIVATE-TOKEN'] = @access_token
res = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: true) do |http|
http.request(req)
end
JSON.parse(res.body)['status'].to_s.to_sym
end
end
end
end
Ignore GitLab API hiccups in lib/gitlab/build/trigger.rb
Signed-off-by: Rémy Coutable <4ea0184b9df19e0786dd00b28e6daa4d26baeb3e@rymai.me>
require 'net/http'
require 'json'
require 'cgi'
module Build
module Trigger
def invoke!(image: nil)
uri = URI("https://gitlab.com/api/v4/projects/#{CGI.escape(get_project_path)}/trigger/pipeline")
params = get_params(image: image)
res = Net::HTTP.post_form(uri, params)
id = JSON.parse(res.body)['id']
raise "Trigger failed! The response from the trigger is: #{res.body}" unless id
puts "Triggered https://gitlab.com/#{get_project_path}/pipelines/#{id}"
puts "Waiting for downstream pipeline status"
Build::Trigger::Pipeline.new(id, get_project_path, get_access_token)
end
class Pipeline
INTERVAL = 60 # seconds
MAX_DURATION = 3600 * 3 # 3 hours
def initialize(id, project_path, access_token)
@start = Time.now.to_i
@access_token = access_token
@uri = URI("https://gitlab.com/api/v4/projects/#{CGI.escape(project_path)}/pipelines/#{id}")
end
def wait!
loop do
raise "Pipeline timed out after waiting for #{duration} minutes!" if timeout?
case status
when :created, :pending, :running
print "."
sleep INTERVAL
when :success
puts "Pipeline succeeded in #{duration} minutes!"
break
else
raise "Pipeline did not succeed!"
end
STDOUT.flush
end
end
def timeout?
Time.now.to_i > (@start + MAX_DURATION)
end
def duration
(Time.now.to_i - @start) / 60
end
def status
req = Net::HTTP::Get.new(@uri)
req['PRIVATE-TOKEN'] = @access_token
res = Net::HTTP.start(@uri.hostname, @uri.port, use_ssl: true) do |http|
http.request(req)
end
JSON.parse(res.body)['status'].to_s.to_sym
rescue JSON::ParserError
# Ignore GitLab API hiccups. If GitLab is really down, we'll hit the job
# timeout anyway.
:running
end
end
end
end
|
require 'rest-client'
require 'oj'
require 'retryable'
module GlobalRegistry
class Base
def initialize(args = {})
@base_url = args[:base_url]
@access_token = args[:access_token]
@xff = args[:xff]
end
def self.find(id, params = {})
request(:get, params, path_with_id(id))
end
def find(id, params = {})
request(:get, params, path_with_id(id))
end
def self.get(params = {})
request(:get, params)
end
def get(params = {})
request(:get, params)
end
def self.post(params = {})
request(:post, params)
end
def post(params = {})
request(:post, params)
end
def self.put(id, params = {})
request(:put, params, path_with_id(id))
end
def put(id, params = {})
request(:put, params, path_with_id(id))
end
def self.delete(id)
request(:delete, {}, path_with_id(id))
end
def delete(id)
request(:delete, {}, path_with_id(id))
end
def self.delete_or_ignore(id)
begin
delete(id)
rescue RestClient::Exception => e
unless e.response.code.to_i == 404
raise
end
end
end
def self.request(method, params, path = nil)
new.request(method, params, path)
end
def request(method, params, path = nil)
raise 'You need to configure GlobalRegistry with your access_token.' unless access_token
path ||= self.class.default_path
url = base_url
url += '/' unless url.last == '/'
url += path
case method
when :post
post_headers = default_headers.merge(content_type: :json, timeout: -1)
RestClient.post(url, params.to_json, post_headers) { |response, request, result, &block|
handle_response(response, request, result)
}
when :put
put_headers = default_headers.merge(content_type: :json, timeout: -1)
RestClient.put(url, params.to_json, put_headers) { |response, request, result, &block|
handle_response(response, request, result)
}
else
get_args = { method: method, url: url, timeout: -1,
headers: default_headers.merge(params: params)
}
RestClient::Request.execute(get_args) { |response, request, result, &block|
handle_response(response, request, result)
}
end
end
def self.default_path
to_s.split('::').last.underscore.pluralize
end
def self.path_with_id(id)
"#{default_path}/#{id}"
end
private
def default_headers
headers = { authorization: "Bearer #{access_token}", accept: :json }
headers = headers.merge('X-Forwarded-For': @xff) if @xff.present?
headers
end
def handle_response(response, request, result)
case response.code
when 200..299
Oj.load(response)
when 400
raise RestClient::BadRequest, response
when 404
raise RestClient::ResourceNotFound, response
when 500
raise RestClient::InternalServerError, response
else
puts response.inspect
puts request.inspect
raise result.to_s
end
end
def base_url
@base_url || GlobalRegistry.base_url
end
def access_token
@access_token || GlobalRegistry.access_token
end
end
end
directly use instance methods from class level methods
require 'rest-client'
require 'oj'
require 'retryable'
module GlobalRegistry
class Base
def initialize(args = {})
@base_url = args[:base_url]
@access_token = args[:access_token]
@xff = args[:xff]
end
def self.find(id, params = {})
new.find(id, params)
end
def find(id, params = {})
request(:get, params, path_with_id(id))
end
def self.get(params = {})
new.get(params)
end
def get(params = {})
request(:get, params)
end
def self.post(params = {})
new.post(params)
end
def post(params = {})
request(:post, params)
end
def self.put(id, params = {})
new.put(id, params)
end
def put(id, params = {})
request(:put, params, path_with_id(id))
end
def self.delete(id)
new.delete(id)
end
def delete(id)
request(:delete, {}, path_with_id(id))
end
def self.delete_or_ignore(id)
delete(id)
rescue RestClient::Exception => e
raise unless e.response.code.to_i == 404
end
def delete_or_ignore(id)
delete(id)
rescue RestClient::Exception => e
raise unless e.response.code.to_i == 404
end
def self.request(method, params, path = nil)
new.request(method, params, path)
end
def request(method, params, path = nil)
raise 'You need to configure GlobalRegistry with your access_token.' unless access_token
path ||= self.class.default_path
url = base_url
url += '/' unless url.last == '/'
url += path
case method
when :post
post_headers = default_headers.merge(content_type: :json, timeout: -1)
RestClient.post(url, params.to_json, post_headers) { |response, request, result, &block|
handle_response(response, request, result)
}
when :put
put_headers = default_headers.merge(content_type: :json, timeout: -1)
RestClient.put(url, params.to_json, put_headers) { |response, request, result, &block|
handle_response(response, request, result)
}
else
get_args = { method: method, url: url, timeout: -1,
headers: default_headers.merge(params: params)
}
RestClient::Request.execute(get_args) { |response, request, result, &block|
handle_response(response, request, result)
}
end
end
def self.default_path
to_s.split('::').last.underscore.pluralize
end
def self.path_with_id(id)
"#{default_path}/#{id}"
end
private
def default_headers
headers = { authorization: "Bearer #{access_token}", accept: :json }
headers = headers.merge('X-Forwarded-For': @xff) if @xff.present?
headers
end
def handle_response(response, request, result)
case response.code
when 200..299
Oj.load(response)
when 400
raise RestClient::BadRequest, response
when 404
raise RestClient::ResourceNotFound, response
when 500
raise RestClient::InternalServerError, response
else
puts response.inspect
puts request.inspect
raise result.to_s
end
end
def base_url
@base_url || GlobalRegistry.base_url
end
def access_token
@access_token || GlobalRegistry.access_token
end
end
end
|
module GlyphFilter
VERSION = "0.0.1"
end
version bump
module GlyphFilter
VERSION = "0.0.2"
end
|
require 'json'
module Precious
module Views
module AppHelpers
def extract_page_dir(path)
return path unless @page_dir
@path_to_extract ||= "#{Pathname.new(@page_dir).cleanpath}/"
path.start_with?(@path_to_extract) ? path.slice(@path_to_extract.length, path.length) : path
end
end
module RouteHelpers
ROUTES = {
'gollum' => {
assets: 'assets',
last_commit_info: 'last_commit_info',
latest_changes: 'latest_changes',
upload_file: 'upload_file',
create: 'create',
delete: 'delete',
edit: 'edit',
overview: 'overview',
history: 'history',
rename: 'rename',
revert: 'revert',
preview: 'preview',
compare: 'compare',
search: 'search'
}
}
def self.parse_routes(routes, prefix = '')
routes.each do |name, path|
if path.respond_to?(:keys)
self.parse_routes(path, "#{prefix}/#{name}")
else
route_path = "#{prefix}/#{path}"
@@route_methods[name.to_s] = route_path
define_method :"#{name.to_s}_path" do
page_route(route_path)
end
end
end
end
def self.included(base)
@@route_methods = {}
self.parse_routes(ROUTES)
define_method :routes_to_json do
@@route_methods.to_json
end
end
def page_route(page = nil)
clean_url(@base_url, page)
end
def clean_url(*url)
url.compact!
return url if url.nil?
::File.join(*url).gsub(%r{/{2,}}, '/')
end
end
module OcticonHelpers
def self.included(base)
def rocticon(symbol, parameters = {})
Octicons::Octicon.new(symbol, parameters).to_svg
end
# Well-formed SVG with XMLNS and height/width removed, for use in CSS
def rocticon_css(symbol, parameters = {})
octicon = ::Octicons::Octicon.new(symbol, parameters.merge({xmlns: 'http://www.w3.org/2000/svg'}))
[:width, :height].each {|option| octicon.options.delete(option)}
octicon.to_svg
end
def octicon
lambda do |args|
symbol, height, width = args.split(' ')
parameters = {}
parameters[:height] = height if height
parameters[:width] = width if width
Octicons::Octicon.new(symbol, parameters).to_svg
end
end
end
end
module SprocketsHelpers
def self.included(base)
def sprockets_stylesheet_tag
lambda do |args|
args = args.split(' ')
name = args[0]
options = {:media => :all}
options[:media] = :print if args[1] == 'print'
send(:stylesheet_tag, name, options)
end
end
def sprockets_asset_path
lambda do |name|
send(:asset_path, name)
end
end
def sprockets_javascript_tag
lambda do |name|
send(:javascript_tag, name)
end
end
def sprockets_image_path
lambda do |args|
send(:image_path, name)
end
end
end
end
end
end
Return nil if url.empty? right after url.comact!
require 'json'
module Precious
module Views
module AppHelpers
def extract_page_dir(path)
return path unless @page_dir
@path_to_extract ||= "#{Pathname.new(@page_dir).cleanpath}/"
path.start_with?(@path_to_extract) ? path.slice(@path_to_extract.length, path.length) : path
end
end
module RouteHelpers
ROUTES = {
'gollum' => {
assets: 'assets',
last_commit_info: 'last_commit_info',
latest_changes: 'latest_changes',
upload_file: 'upload_file',
create: 'create',
delete: 'delete',
edit: 'edit',
overview: 'overview',
history: 'history',
rename: 'rename',
revert: 'revert',
preview: 'preview',
compare: 'compare',
search: 'search'
}
}
def self.parse_routes(routes, prefix = '')
routes.each do |name, path|
if path.respond_to?(:keys)
self.parse_routes(path, "#{prefix}/#{name}")
else
route_path = "#{prefix}/#{path}"
@@route_methods[name.to_s] = route_path
define_method :"#{name.to_s}_path" do
page_route(route_path)
end
end
end
end
def self.included(base)
@@route_methods = {}
self.parse_routes(ROUTES)
define_method :routes_to_json do
@@route_methods.to_json
end
end
def page_route(page = nil)
clean_url(@base_url, page)
end
def clean_url(*url)
url.compact!
return nil if url.empty?
::File.join(*url).gsub(%r{/{2,}}, '/')
end
end
module OcticonHelpers
def self.included(base)
def rocticon(symbol, parameters = {})
Octicons::Octicon.new(symbol, parameters).to_svg
end
# Well-formed SVG with XMLNS and height/width removed, for use in CSS
def rocticon_css(symbol, parameters = {})
octicon = ::Octicons::Octicon.new(symbol, parameters.merge({xmlns: 'http://www.w3.org/2000/svg'}))
[:width, :height].each {|option| octicon.options.delete(option)}
octicon.to_svg
end
def octicon
lambda do |args|
symbol, height, width = args.split(' ')
parameters = {}
parameters[:height] = height if height
parameters[:width] = width if width
Octicons::Octicon.new(symbol, parameters).to_svg
end
end
end
end
module SprocketsHelpers
def self.included(base)
def sprockets_stylesheet_tag
lambda do |args|
args = args.split(' ')
name = args[0]
options = {:media => :all}
options[:media] = :print if args[1] == 'print'
send(:stylesheet_tag, name, options)
end
end
def sprockets_asset_path
lambda do |name|
send(:asset_path, name)
end
end
def sprockets_javascript_tag
lambda do |name|
send(:javascript_tag, name)
end
end
def sprockets_image_path
lambda do |args|
send(:image_path, name)
end
end
end
end
end
end
|
# encoding: utf-8
require 'rest-client'
require_relative '../helpers/auth_helpers'
require_relative 'connections/connections'
require_relative 'object_factory'
require_relative '../mixins/inspector'
module GoodData
module Rest
# User's interface to GoodData Platform.
#
# MUST provide way to use - DELETE, GET, POST, PUT
# SHOULD provide way to use - HEAD, Bulk GET ...
class Client
#################################
# Constants
#################################
DEFAULT_CONNECTION_IMPLEMENTATION = Connections::RestClientConnection
RETRYABLE_ERRORS = [
SystemCallError,
RestClient::InternalServerError,
RestClient::RequestTimeout
]
#################################
# Class variables
#################################
@@instance = nil # rubocop:disable ClassVars
#################################
# Getters/Setters
#################################
# Decide if we need provide direct access to connection
attr_reader :connection
# TODO: Decide if we need provide direct access to factory
attr_reader :factory
attr_reader :opts
include Mixin::Inspector
inspector :object_id
#################################
# Class methods
#################################
class << self
# Globally available way to connect (and create client and set global instance)
#
# ## HACK
# To make transition from old implementation to new one following HACK IS TEMPORARILY ENGAGED!
#
# 1. First call of #connect sets the GoodData::Rest::Client.instance (static, singleton instance)
# 2. There are METHOD functions with same signature as their CLASS counterparts using singleton instance
#
# ## Example
#
# client = GoodData.connect('jon.smith@goodddata.com', 's3cr3tp4sw0rd')
#
# @param username [String] Username to be used for authentication
# @param password [String] Password to be used for authentication
# @return [GoodData::Rest::Client] Client
def connect(username, password, opts = { :verify_ssl => true })
new_opts = opts.dup
if username.is_a?(Hash) && username.key?(:sst_token)
new_opts[:sst_token] = username[:sst_token]
elsif username.is_a? Hash
new_opts[:username] = username[:login] || username[:user] || username[:username]
new_opts[:password] = username[:password]
elsif username.nil? && password.nil? && (opts.nil? || opts.empty?)
new_opts = Helpers::AuthHelper.read_credentials
else
new_opts[:username] = username
new_opts[:password] = password
end
unless new_opts[:sst_token]
fail ArgumentError, 'No username specified' if new_opts[:username].nil?
fail ArgumentError, 'No password specified' if new_opts[:password].nil?
end
if username.is_a?(Hash) && username.key?(:server)
new_opts[:server] = username[:server]
end
client = Client.new(new_opts)
if client
at_exit do
# puts client.connection.stats_table if client && client.connection
end
end
# HACK: This line assigns class instance # if not done yet
@@instance = client # rubocop:disable ClassVars
client
end
def disconnect
if @@instance # rubocop:disable ClassVars, Style/GuardClause
@@instance.disconnect # rubocop:disable ClassVars
@@instance = nil # rubocop:disable ClassVars
end
end
def connection
@@instance # rubocop:disable ClassVars
end
# Retry block if exception thrown
def retryable(options = {}, &_block)
opts = { :tries => 1, :on => RETRYABLE_ERRORS }.merge(options)
retry_exception, retries = opts[:on], opts[:tries]
unless retry_exception.is_a?(Array)
retry_exception = [retry_exception]
end
retry_time = 1
begin
return yield
rescue RestClient::TooManyRequests
GoodData.logger.warn "Too many requests, retrying in #{retry_time} seconds"
sleep retry_time
retry_time *= 1.5
retry
rescue *retry_exception
retry if (retries -= 1) > 0
end
yield
end
alias_method :client, :connection
end
# Constructor of client
# @param opts [Hash] Client options
# @option opts [String] :username Username used for authentication
# @option opts [String] :password Password used for authentication
# @option opts :connection_factory Object able to create new instances of GoodData::Rest::Connection
# @option opts [GoodData::Rest::Connection] :connection Existing GoodData::Rest::Connection
def initialize(opts)
# TODO: Decide if we want to pass the options directly or not
@opts = opts
@connection_factory = @opts[:connection_factory] || DEFAULT_CONNECTION_IMPLEMENTATION
# TODO: See previous TODO
# Create connection
@connection = opts[:connection] || @connection_factory.new(opts)
# Connect
connect
# Create factory bound to previously created connection
@factory = ObjectFactory.new(self)
end
def create_project(options = { title: 'Project', auth_token: ENV['GD_PROJECT_TOKEN'] })
GoodData::Project.create(options.merge(client: self))
end
def create_project_from_blueprint(blueprint, options = {})
GoodData::Model::ProjectCreator.migrate(spec: blueprint, token: options[:auth_token], client: self)
end
def domain(domain_name)
GoodData::Domain[domain_name, :client => self]
end
def projects(id = :all)
GoodData::Project[id, client: self]
end
def processes(id = :all)
GoodData::Process[id, client: self]
end
def connect
username = @opts[:username]
password = @opts[:password]
@connection.connect(username, password, @opts)
end
def disconnect
@connection.disconnect
end
#######################
# Factory stuff
######################
def create(klass, data = {}, opts = {})
@factory.create(klass, data, opts)
end
def find(klass, opts = {})
@factory.find(klass, opts)
end
# Gets resource by name
def resource(res_name)
puts "Getting resource '#{res_name}'"
nil
end
def user
create(GoodData::Profile, @connection.user)
end
#######################
# Rest
#######################
# HTTP DELETE
#
# @param uri [String] Target URI
def delete(uri, opts = {})
@connection.delete uri, opts
end
# HTTP GET
#
# @param uri [String] Target URI
def get(uri, opts = {}, & block)
@connection.get uri, opts, & block
end
# FIXME: Invstigate _file argument
def get_project_webdav_path(_file, opts = { :project => GoodData.project })
p = opts[:project]
fail ArgumentError, 'No :project specified' if p.nil?
project = GoodData::Project[p, opts]
fail ArgumentError, 'Wrong :project specified' if project.nil?
u = URI(project.links['uploads'])
URI.join(u.to_s.chomp(u.path.to_s), '/project-uploads/', "#{project.pid}/")
end
# FIXME: Invstigate _file argument
def get_user_webdav_path(_file, opts = { :project => GoodData.project })
p = opts[:project]
fail ArgumentError, 'No :project specified' if p.nil?
project = GoodData::Project[p, opts]
fail ArgumentError, 'Wrong :project specified' if project.nil?
u = URI(project.links['uploads'])
URI.join(u.to_s.chomp(u.path.to_s), '/uploads/')
end
# Generalizaton of poller. Since we have quite a variation of how async proceses are handled
# this is a helper that should help you with resources where the information about "Are we done"
# is the http code of response. By default we repeat as long as the code == 202. You can
# change the code if necessary. It expects the URI as an input where it can poll. It returns the
# value of last poll. In majority of cases these are the data that you need.
#
# @param link [String] Link for polling
# @param options [Hash] Options
# @return [Hash] Result of polling
def poll_on_code(link, options = {})
code = options[:code] || 202
sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL
response = get(link, :process => false)
while response.code == code
sleep sleep_interval
GoodData::Rest::Client.retryable(:tries => 3) do
sleep sleep_interval
response = get(link, :process => false)
end
end
if options[:process] == false
response
else
get(link)
end
end
# Generalizaton of poller. Since we have quite a variation of how async proceses are handled
# this is a helper that should help you with resources where the information about "Are we done"
# is inside the response. It expects the URI as an input where it can poll and a block that should
# return either true -> 'meaning we are done' or false -> meaning sleep and repeat. It returns the
# value of last poll. In majority of cases these are the data that you need
#
# @param link [String] Link for polling
# @param options [Hash] Options
# @return [Hash] Result of polling
def poll_on_response(link, options = {}, &bl)
sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL
response = get(link)
while bl.call(response)
sleep sleep_interval
GoodData::Rest::Client.retryable(:tries => 3) do
sleep sleep_interval
response = get(link)
end
end
response
end
# HTTP PUT
#
# @param uri [String] Target URI
def put(uri, data, opts = {})
@connection.put uri, data, opts
end
# HTTP POST
#
# @param uri [String] Target URI
def post(uri, data, opts = {})
@connection.post uri, data, opts
end
# Uploads file to staging
#
# @param file [String] file to be uploaded
# @param options [Hash] must contain :staging_url key (file will be uploaded to :staging_url + File.basename(file))
def upload(file, options = {})
@connection.upload file, options
end
# Downloads file from staging
#
# @param source_relative_path [String] path relative to @param options[:staging_url]
# @param target_file_path [String] path to be downloaded to
# @param options [Hash] must contain :staging_url key (file will be downloaded from :staging_url + source_relative_path)
def download(source_relative_path, target_file_path, options = {})
@connection.download source_relative_path, target_file_path, options
end
def download_from_user_webdav(source_relative_path, target_file_path, options = {})
download(source_relative_path, target_file_path, options.merge(
:directory => options[:directory],
:staging_url => get_user_webdav_url(options)
))
end
def upload_to_user_webdav(file, options = {})
upload(file, options.merge(
:directory => options[:directory],
:staging_url => get_user_webdav_url(options)
))
end
def with_project(pid, &block)
GoodData.with_project(pid, client: self, &block)
end
###################### PRIVATE ######################
private
def get_user_webdav_url(options = {})
p = options[:project]
fail ArgumentError, 'No :project specified' if p.nil?
project = options[:project] || GoodData::Project[p, options]
fail ArgumentError, 'Wrong :project specified' if project.nil?
u = URI(project.links['uploads'])
us = u.to_s
ws = options[:client].opts[:webdav_server]
if !us.empty? && !us.downcase.start_with?('http') && !ws.empty?
u = URI.join(ws, us)
end
URI.join(u.to_s.chomp(u.path.to_s), '/uploads/')
end
end
end
end
Add Net::ReadTimeout to list of RETRYABLE_ERRORS
# encoding: utf-8
require 'rest-client'
require_relative '../helpers/auth_helpers'
require_relative 'connections/connections'
require_relative 'object_factory'
require_relative '../mixins/inspector'
module GoodData
module Rest
# User's interface to GoodData Platform.
#
# MUST provide way to use - DELETE, GET, POST, PUT
# SHOULD provide way to use - HEAD, Bulk GET ...
class Client
#################################
# Constants
#################################
DEFAULT_CONNECTION_IMPLEMENTATION = Connections::RestClientConnection
RETRYABLE_ERRORS = [
Net::ReadTimeout,
RestClient::InternalServerError,
RestClient::RequestTimeout,
SystemCallError
]
#################################
# Class variables
#################################
@@instance = nil # rubocop:disable ClassVars
#################################
# Getters/Setters
#################################
# Decide if we need provide direct access to connection
attr_reader :connection
# TODO: Decide if we need provide direct access to factory
attr_reader :factory
attr_reader :opts
include Mixin::Inspector
inspector :object_id
#################################
# Class methods
#################################
class << self
# Globally available way to connect (and create client and set global instance)
#
# ## HACK
# To make transition from old implementation to new one following HACK IS TEMPORARILY ENGAGED!
#
# 1. First call of #connect sets the GoodData::Rest::Client.instance (static, singleton instance)
# 2. There are METHOD functions with same signature as their CLASS counterparts using singleton instance
#
# ## Example
#
# client = GoodData.connect('jon.smith@goodddata.com', 's3cr3tp4sw0rd')
#
# @param username [String] Username to be used for authentication
# @param password [String] Password to be used for authentication
# @return [GoodData::Rest::Client] Client
def connect(username, password, opts = { :verify_ssl => true })
new_opts = opts.dup
if username.is_a?(Hash) && username.key?(:sst_token)
new_opts[:sst_token] = username[:sst_token]
elsif username.is_a? Hash
new_opts[:username] = username[:login] || username[:user] || username[:username]
new_opts[:password] = username[:password]
elsif username.nil? && password.nil? && (opts.nil? || opts.empty?)
new_opts = Helpers::AuthHelper.read_credentials
else
new_opts[:username] = username
new_opts[:password] = password
end
unless new_opts[:sst_token]
fail ArgumentError, 'No username specified' if new_opts[:username].nil?
fail ArgumentError, 'No password specified' if new_opts[:password].nil?
end
if username.is_a?(Hash) && username.key?(:server)
new_opts[:server] = username[:server]
end
client = Client.new(new_opts)
if client
at_exit do
# puts client.connection.stats_table if client && client.connection
end
end
# HACK: This line assigns class instance # if not done yet
@@instance = client # rubocop:disable ClassVars
client
end
def disconnect
if @@instance # rubocop:disable ClassVars, Style/GuardClause
@@instance.disconnect # rubocop:disable ClassVars
@@instance = nil # rubocop:disable ClassVars
end
end
def connection
@@instance # rubocop:disable ClassVars
end
# Retry block if exception thrown
def retryable(options = {}, &_block)
opts = { :tries => 1, :on => RETRYABLE_ERRORS }.merge(options)
retry_exception, retries = opts[:on], opts[:tries]
unless retry_exception.is_a?(Array)
retry_exception = [retry_exception]
end
retry_time = 1
begin
return yield
rescue RestClient::TooManyRequests
GoodData.logger.warn "Too many requests, retrying in #{retry_time} seconds"
sleep retry_time
retry_time *= 1.5
retry
rescue *retry_exception
retry if (retries -= 1) > 0
end
yield
end
alias_method :client, :connection
end
# Constructor of client
# @param opts [Hash] Client options
# @option opts [String] :username Username used for authentication
# @option opts [String] :password Password used for authentication
# @option opts :connection_factory Object able to create new instances of GoodData::Rest::Connection
# @option opts [GoodData::Rest::Connection] :connection Existing GoodData::Rest::Connection
def initialize(opts)
# TODO: Decide if we want to pass the options directly or not
@opts = opts
@connection_factory = @opts[:connection_factory] || DEFAULT_CONNECTION_IMPLEMENTATION
# TODO: See previous TODO
# Create connection
@connection = opts[:connection] || @connection_factory.new(opts)
# Connect
connect
# Create factory bound to previously created connection
@factory = ObjectFactory.new(self)
end
def create_project(options = { title: 'Project', auth_token: ENV['GD_PROJECT_TOKEN'] })
GoodData::Project.create(options.merge(client: self))
end
def create_project_from_blueprint(blueprint, options = {})
GoodData::Model::ProjectCreator.migrate(spec: blueprint, token: options[:auth_token], client: self)
end
def domain(domain_name)
GoodData::Domain[domain_name, :client => self]
end
def projects(id = :all)
GoodData::Project[id, client: self]
end
def processes(id = :all)
GoodData::Process[id, client: self]
end
def connect
username = @opts[:username]
password = @opts[:password]
@connection.connect(username, password, @opts)
end
def disconnect
@connection.disconnect
end
#######################
# Factory stuff
######################
def create(klass, data = {}, opts = {})
@factory.create(klass, data, opts)
end
def find(klass, opts = {})
@factory.find(klass, opts)
end
# Gets resource by name
def resource(res_name)
puts "Getting resource '#{res_name}'"
nil
end
def user
create(GoodData::Profile, @connection.user)
end
#######################
# Rest
#######################
# HTTP DELETE
#
# @param uri [String] Target URI
def delete(uri, opts = {})
@connection.delete uri, opts
end
# HTTP GET
#
# @param uri [String] Target URI
def get(uri, opts = {}, & block)
@connection.get uri, opts, & block
end
# FIXME: Invstigate _file argument
def get_project_webdav_path(_file, opts = { :project => GoodData.project })
p = opts[:project]
fail ArgumentError, 'No :project specified' if p.nil?
project = GoodData::Project[p, opts]
fail ArgumentError, 'Wrong :project specified' if project.nil?
u = URI(project.links['uploads'])
URI.join(u.to_s.chomp(u.path.to_s), '/project-uploads/', "#{project.pid}/")
end
# FIXME: Invstigate _file argument
def get_user_webdav_path(_file, opts = { :project => GoodData.project })
p = opts[:project]
fail ArgumentError, 'No :project specified' if p.nil?
project = GoodData::Project[p, opts]
fail ArgumentError, 'Wrong :project specified' if project.nil?
u = URI(project.links['uploads'])
URI.join(u.to_s.chomp(u.path.to_s), '/uploads/')
end
# Generalizaton of poller. Since we have quite a variation of how async proceses are handled
# this is a helper that should help you with resources where the information about "Are we done"
# is the http code of response. By default we repeat as long as the code == 202. You can
# change the code if necessary. It expects the URI as an input where it can poll. It returns the
# value of last poll. In majority of cases these are the data that you need.
#
# @param link [String] Link for polling
# @param options [Hash] Options
# @return [Hash] Result of polling
def poll_on_code(link, options = {})
code = options[:code] || 202
sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL
response = get(link, :process => false)
while response.code == code
sleep sleep_interval
GoodData::Rest::Client.retryable(:tries => 3) do
sleep sleep_interval
response = get(link, :process => false)
end
end
if options[:process] == false
response
else
get(link)
end
end
# Generalizaton of poller. Since we have quite a variation of how async proceses are handled
# this is a helper that should help you with resources where the information about "Are we done"
# is inside the response. It expects the URI as an input where it can poll and a block that should
# return either true -> 'meaning we are done' or false -> meaning sleep and repeat. It returns the
# value of last poll. In majority of cases these are the data that you need
#
# @param link [String] Link for polling
# @param options [Hash] Options
# @return [Hash] Result of polling
def poll_on_response(link, options = {}, &bl)
sleep_interval = options[:sleep_interval] || DEFAULT_SLEEP_INTERVAL
response = get(link)
while bl.call(response)
sleep sleep_interval
GoodData::Rest::Client.retryable(:tries => 3) do
sleep sleep_interval
response = get(link)
end
end
response
end
# HTTP PUT
#
# @param uri [String] Target URI
def put(uri, data, opts = {})
@connection.put uri, data, opts
end
# HTTP POST
#
# @param uri [String] Target URI
def post(uri, data, opts = {})
@connection.post uri, data, opts
end
# Uploads file to staging
#
# @param file [String] file to be uploaded
# @param options [Hash] must contain :staging_url key (file will be uploaded to :staging_url + File.basename(file))
def upload(file, options = {})
@connection.upload file, options
end
# Downloads file from staging
#
# @param source_relative_path [String] path relative to @param options[:staging_url]
# @param target_file_path [String] path to be downloaded to
# @param options [Hash] must contain :staging_url key (file will be downloaded from :staging_url + source_relative_path)
def download(source_relative_path, target_file_path, options = {})
@connection.download source_relative_path, target_file_path, options
end
def download_from_user_webdav(source_relative_path, target_file_path, options = {})
download(source_relative_path, target_file_path, options.merge(
:directory => options[:directory],
:staging_url => get_user_webdav_url(options)
))
end
def upload_to_user_webdav(file, options = {})
upload(file, options.merge(
:directory => options[:directory],
:staging_url => get_user_webdav_url(options)
))
end
def with_project(pid, &block)
GoodData.with_project(pid, client: self, &block)
end
###################### PRIVATE ######################
private
def get_user_webdav_url(options = {})
p = options[:project]
fail ArgumentError, 'No :project specified' if p.nil?
project = options[:project] || GoodData::Project[p, options]
fail ArgumentError, 'Wrong :project specified' if project.nil?
u = URI(project.links['uploads'])
us = u.to_s
ws = options[:client].opts[:webdav_server]
if !us.empty? && !us.downcase.start_with?('http') && !ws.empty?
u = URI.join(ws, us)
end
URI.join(u.to_s.chomp(u.path.to_s), '/uploads/')
end
end
end
end
|
module GraphQLDocs
VERSION = '1.0.0.pre'
end
Bump to 1.0.0.pre1
module GraphQLDocs
VERSION = '1.0.0.pre1'
end
|
# frozen_string_literal: true
require "graphql/schema/field/connection_extension"
require "graphql/schema/field/scope_extension"
module GraphQL
class Schema
class Field
include GraphQL::Schema::Member::HasArguments
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasPath
include GraphQL::Schema::Member::HasValidators
extend GraphQL::Schema::FindInheritedValue
include GraphQL::Schema::FindInheritedValue::EmptyObjects
include GraphQL::Schema::Member::HasDirectives
include GraphQL::Schema::Member::HasDeprecationReason
class FieldImplementationFailed < GraphQL::Error; end
# @return [String] the GraphQL name for this field, camelized unless `camelize: false` is provided
attr_reader :name
alias :graphql_name :name
attr_writer :description
# @return [Symbol] Method or hash key on the underlying object to look up
attr_reader :method_sym
# @return [String] Method or hash key on the underlying object to look up
attr_reader :method_str
attr_reader :hash_key
attr_reader :dig_keys
# @return [Symbol] The method on the type to look up
def resolver_method
if @resolver_class
@resolver_class.resolver_method
else
@resolver_method
end
end
# @return [Class] The thing this field was defined on (type, mutation, resolver)
attr_accessor :owner
# @return [Class] The GraphQL type this field belongs to. (For fields defined on mutations, it's the payload type)
def owner_type
@owner_type ||= if owner.nil?
raise GraphQL::InvariantError, "Field #{original_name.inspect} (graphql name: #{graphql_name.inspect}) has no owner, but all fields should have an owner. How did this happen?!"
elsif owner < GraphQL::Schema::Mutation
owner.payload_type
else
owner
end
end
# @return [Symbol] the original name of the field, passed in by the user
attr_reader :original_name
# @return [Class, nil] The {Schema::Resolver} this field was derived from, if there is one
def resolver
@resolver_class
end
# @return [Boolean] Is this field a predefined introspection field?
def introspection?
@introspection
end
def inspect
"#<#{self.class} #{path}#{all_argument_definitions.any? ? "(...)" : ""}: #{type.to_type_signature}>"
end
alias :mutation :resolver
# @return [Boolean] Apply tracing to this field? (Default: skip scalars, this is the override value)
attr_reader :trace
# @return [String, nil]
def subscription_scope
@subscription_scope || (@resolver_class.respond_to?(:subscription_scope) ? @resolver_class.subscription_scope : nil)
end
attr_writer :subscription_scope
# Create a field instance from a list of arguments, keyword arguments, and a block.
#
# This method implements prioritization between the `resolver` or `mutation` defaults
# and the local overrides via other keywords.
#
# It also normalizes positional arguments into keywords for {Schema::Field#initialize}.
# @param resolver [Class] A {GraphQL::Schema::Resolver} class to use for field configuration
# @param mutation [Class] A {GraphQL::Schema::Mutation} class to use for field configuration
# @param subscription [Class] A {GraphQL::Schema::Subscription} class to use for field configuration
# @return [GraphQL::Schema:Field] an instance of `self
# @see {.initialize} for other options
def self.from_options(name = nil, type = nil, desc = nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
if (resolver_class = resolver || mutation || subscription)
# Add a reference to that parent class
kwargs[:resolver_class] = resolver_class
end
if name
kwargs[:name] = name
end
if !type.nil?
if desc
if kwargs[:description]
raise ArgumentError, "Provide description as a positional argument or `description:` keyword, but not both (#{desc.inspect}, #{kwargs[:description].inspect})"
end
kwargs[:description] = desc
kwargs[:type] = type
elsif (resolver || mutation) && type.is_a?(String)
# The return type should be copied from the resolver, and the second positional argument is the description
kwargs[:description] = type
else
kwargs[:type] = type
end
if type.is_a?(Class) && type < GraphQL::Schema::Mutation
raise ArgumentError, "Use `field #{name.inspect}, mutation: Mutation, ...` to provide a mutation to this field instead"
end
end
new(**kwargs, &block)
end
# Can be set with `connection: true|false` or inferred from a type name ending in `*Connection`
# @return [Boolean] if true, this field will be wrapped with Relay connection behavior
def connection?
if @connection.nil?
# Provide default based on type name
return_type_name = if @resolver_class && @resolver_class.type
Member::BuildType.to_type_name(@resolver_class.type)
elsif @return_type_expr
Member::BuildType.to_type_name(@return_type_expr)
else
# As a last ditch, try to force loading the return type:
type.unwrap.name
end
@connection = return_type_name.end_with?("Connection")
else
@connection
end
end
# @return [Boolean] if true, the return type's `.scope_items` method will be applied to this field's return value
def scoped?
if !@scope.nil?
# The default was overridden
@scope
elsif @return_type_expr
# Detect a list return type, but don't call `type` since that may eager-load an otherwise lazy-loaded type
@return_type_expr.is_a?(Array) ||
(@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) ||
connection?
elsif @resolver_class
resolver_type = @resolver_class.type_expr
resolver_type.is_a?(Array) ||
(resolver_type.is_a?(String) && resolver_type.include?("[")) ||
connection?
else
false
end
end
# This extension is applied to fields when {#connection?} is true.
#
# You can override it in your base field definition.
# @return [Class] A {FieldExtension} subclass for implementing pagination behavior.
# @example Configuring a custom extension
# class Types::BaseField < GraphQL::Schema::Field
# connection_extension(MyCustomExtension)
# end
def self.connection_extension(new_extension_class = nil)
if new_extension_class
@connection_extension = new_extension_class
else
@connection_extension ||= find_inherited_value(:connection_extension, ConnectionExtension)
end
end
# @return Boolean
attr_reader :relay_node_field
# @return Boolean
attr_reader :relay_nodes_field
# @return [Boolean] Should we warn if this field's name conflicts with a built-in method?
def method_conflict_warning?
@method_conflict_warning
end
# @param name [Symbol] The underscore-cased version of this field name (will be camelized for the GraphQL API)
# @param type [Class, GraphQL::BaseType, Array] The return type of this field
# @param owner [Class] The type that this field belongs to
# @param null [Boolean] (defaults to `true`) `true` if this field may return `null`, `false` if it is never `null`
# @param description [String] Field description
# @param deprecation_reason [String] If present, the field is marked "deprecated" with this message
# @param method [Symbol] The method to call on the underlying object to resolve this field (defaults to `name`)
# @param hash_key [String, Symbol] The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults to `name` or `name.to_s`)
# @param dig [Array<String, Symbol>] The nested hash keys to lookup on the underlying hash to resolve this field using dig
# @param resolver_method [Symbol] The method on the type to call to resolve this field (defaults to `name`)
# @param connection [Boolean] `true` if this field should get automagic connection behavior; default is to infer by `*Connection` in the return type name
# @param connection_extension [Class] The extension to add, to implement connections. If `nil`, no extension is added.
# @param max_page_size [Integer, nil] For connections, the maximum number of items to return from this field, or `nil` to allow unlimited results.
# @param default_page_size [Integer, nil] For connections, the default number of items to return from this field, or `nil` to return unlimited results.
# @param introspection [Boolean] If true, this field will be marked as `#introspection?` and the name may begin with `__`
# @param resolver_class [Class] (Private) A {Schema::Resolver} which this field was derived from. Use `resolver:` to create a field with a resolver.
# @param arguments [{String=>GraphQL::Schema::Argument, Hash}] Arguments for this field (may be added in the block, also)
# @param camelize [Boolean] If true, the field name will be camelized when building the schema
# @param complexity [Numeric] When provided, set the complexity for this field
# @param scope [Boolean] If true, the return type's `.scope_items` method will be called on the return value
# @param subscription_scope [Symbol, String] A key in `context` which will be used to scope subscription payloads
# @param extensions [Array<Class, Hash<Class => Object>>] Named extensions to apply to this field (see also {#extension})
# @param directives [Hash{Class => Hash}] Directives to apply to this field
# @param trace [Boolean] If true, a {GraphQL::Tracing} tracer will measure this scalar field
# @param broadcastable [Boolean] Whether or not this field can be distributed in subscription broadcasts
# @param ast_node [Language::Nodes::FieldDefinition, nil] If this schema was parsed from definition, this AST node defined the field
# @param method_conflict_warning [Boolean] If false, skip the warning if this field's method conflicts with a built-in method
# @param validates [Array<Hash>] Configurations for validating this field
# @fallback_value [Object] A fallback value if the method is not defined
def initialize(type: nil, name: nil, owner: nil, null: nil, description: :not_given, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: :not_given, default_page_size: :not_given, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, ast_node: nil, extras: EMPTY_ARRAY, extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, broadcastable: nil, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, fallback_value: :not_given, &definition_block)
if name.nil?
raise ArgumentError, "missing first `name` argument or keyword `name:`"
end
if !(resolver_class)
if type.nil?
raise ArgumentError, "missing second `type` argument or keyword `type:`"
end
end
@original_name = name
name_s = -name.to_s
@underscored_name = -Member::BuildType.underscore(name_s)
@name = -(camelize ? Member::BuildType.camelize(name_s) : name_s)
if description != :not_given
@description = description
end
self.deprecation_reason = deprecation_reason
if method && hash_key && dig
raise ArgumentError, "Provide `method:`, `hash_key:` _or_ `dig:`, not multiple. (called with: `method: #{method.inspect}, hash_key: #{hash_key.inspect}, dig: #{dig.inspect}`)"
end
if resolver_method
if method
raise ArgumentError, "Provide `method:` _or_ `resolver_method:`, not both. (called with: `method: #{method.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
if hash_key || dig
raise ArgumentError, "Provide `hash_key:`, `dig:`, _or_ `resolver_method:`, not multiple. (called with: `hash_key: #{hash_key.inspect}, dig: #{dig.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
end
method_name = method || hash_key || name_s
@dig_keys = dig
if hash_key
@hash_key = hash_key.to_sym
@hash_key_str = hash_key.to_s
end
@method_str = -method_name.to_s
@method_sym = method_name.to_sym
@resolver_method = (resolver_method || name_s).to_sym
@complexity = complexity
@return_type_expr = type
@return_type_null = if !null.nil?
null
elsif resolver_class
nil
else
true
end
@connection = connection
@has_max_page_size = max_page_size != :not_given
@max_page_size = max_page_size == :not_given ? nil : max_page_size
@has_default_page_size = default_page_size != :not_given
@default_page_size = default_page_size == :not_given ? nil : default_page_size
@introspection = introspection
@extras = extras
if !broadcastable.nil?
@broadcastable = broadcastable
end
@resolver_class = resolver_class
@scope = scope
@trace = trace
@relay_node_field = relay_node_field
@relay_nodes_field = relay_nodes_field
@ast_node = ast_node
@method_conflict_warning = method_conflict_warning
@fallback_value = fallback_value
arguments.each do |name, arg|
case arg
when Hash
argument(name: name, **arg)
when GraphQL::Schema::Argument
add_argument(arg)
when Array
arg.each { |a| add_argument(a) }
else
raise ArgumentError, "Unexpected argument config (#{arg.class}): #{arg.inspect}"
end
end
@owner = owner
@subscription_scope = subscription_scope
@extensions = EMPTY_ARRAY
@call_after_define = false
# This should run before connection extension,
# but should it run after the definition block?
if scoped?
self.extension(ScopeExtension)
end
# The problem with putting this after the definition_block
# is that it would override arguments
if connection? && connection_extension
self.extension(connection_extension)
end
# Do this last so we have as much context as possible when initializing them:
if extensions.any?
self.extensions(extensions)
end
if resolver_class && resolver_class.extensions.any?
self.extensions(resolver_class.extensions)
end
if directives.any?
directives.each do |(dir_class, options)|
self.directive(dir_class, **options)
end
end
if !validates.empty?
self.validates(validates)
end
if definition_block
if definition_block.arity == 1
yield self
else
instance_eval(&definition_block)
end
end
self.extensions.each(&:after_define_apply)
@call_after_define = true
end
# If true, subscription updates with this field can be shared between viewers
# @return [Boolean, nil]
# @see GraphQL::Subscriptions::BroadcastAnalyzer
def broadcastable?
if defined?(@broadcastable)
@broadcastable
elsif @resolver_class
@resolver_class.broadcastable?
else
nil
end
end
# @param text [String]
# @return [String]
def description(text = nil)
if text
@description = text
elsif defined?(@description)
@description
elsif @resolver_class
@description || @resolver_class.description
else
nil
end
end
# Read extension instances from this field,
# or add new classes/options to be initialized on this field.
# Extensions are executed in the order they are added.
#
# @example adding an extension
# extensions([MyExtensionClass])
#
# @example adding multiple extensions
# extensions([MyExtensionClass, AnotherExtensionClass])
#
# @example adding an extension with options
# extensions([MyExtensionClass, { AnotherExtensionClass => { filter: true } }])
#
# @param extensions [Array<Class, Hash<Class => Hash>>] Add extensions to this field. For hash elements, only the first key/value is used.
# @return [Array<GraphQL::Schema::FieldExtension>] extensions to apply to this field
def extensions(new_extensions = nil)
if new_extensions
new_extensions.each do |extension_config|
if extension_config.is_a?(Hash)
extension_class, options = *extension_config.to_a[0]
self.extension(extension_class, options)
else
self.extension(extension_config)
end
end
end
@extensions
end
# Add `extension` to this field, initialized with `options` if provided.
#
# @example adding an extension
# extension(MyExtensionClass)
#
# @example adding an extension with options
# extension(MyExtensionClass, filter: true)
#
# @param extension_class [Class] subclass of {Schema::FieldExtension}
# @param options [Hash] if provided, given as `options:` when initializing `extension`.
# @return [void]
def extension(extension_class, options = nil)
extension_inst = extension_class.new(field: self, options: options)
if @extensions.frozen?
@extensions = @extensions.dup
end
if @call_after_define
extension_inst.after_define_apply
end
@extensions << extension_inst
nil
end
# Read extras (as symbols) from this field,
# or add new extras to be opted into by this field's resolver.
#
# @param new_extras [Array<Symbol>] Add extras to this field
# @return [Array<Symbol>]
def extras(new_extras = nil)
if new_extras.nil?
# Read the value
field_extras = @extras
if @resolver_class && @resolver_class.extras.any?
field_extras + @resolver_class.extras
else
field_extras
end
else
if @extras.frozen?
@extras = @extras.dup
end
# Append to the set of extras on this field
@extras.concat(new_extras)
end
end
def calculate_complexity(query:, nodes:, child_complexity:)
if respond_to?(:complexity_for)
lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
complexity_for(child_complexity: child_complexity, query: query, lookahead: lookahead)
elsif connection?
arguments = query.arguments_for(nodes.first, self)
max_possible_page_size = nil
if arguments.respond_to?(:[]) # It might have been an error
if arguments[:first]
max_possible_page_size = arguments[:first]
end
if arguments[:last] && (max_possible_page_size.nil? || arguments[:last] > max_possible_page_size)
max_possible_page_size = arguments[:last]
end
end
if max_possible_page_size.nil?
max_possible_page_size = default_page_size || query.schema.default_page_size || max_page_size || query.schema.default_max_page_size
end
if max_possible_page_size.nil?
raise GraphQL::Error, "Can't calculate complexity for #{path}, no `first:`, `last:`, `default_page_size`, `max_page_size` or `default_max_page_size`"
else
metadata_complexity = 0
lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
if (page_info_lookahead = lookahead.selection(:page_info)).selected?
metadata_complexity += 1 # pageInfo
metadata_complexity += page_info_lookahead.selections.size # subfields
end
if lookahead.selects?(:total) || lookahead.selects?(:total_count) || lookahead.selects?(:count)
metadata_complexity += 1
end
nodes_edges_complexity = 0
nodes_edges_complexity += 1 if lookahead.selects?(:edges)
nodes_edges_complexity += 1 if lookahead.selects?(:nodes)
# Possible bug: selections on `edges` and `nodes` are _both_ multiplied here. Should they be?
items_complexity = child_complexity - metadata_complexity - nodes_edges_complexity
# Add 1 for _this_ field
1 + (max_possible_page_size * items_complexity) + metadata_complexity + nodes_edges_complexity
end
else
defined_complexity = complexity
case defined_complexity
when Proc
arguments = query.arguments_for(nodes.first, self)
if arguments.is_a?(GraphQL::ExecutionError)
return child_complexity
elsif arguments.respond_to?(:keyword_arguments)
arguments = arguments.keyword_arguments
end
defined_complexity.call(query.context, arguments, child_complexity)
when Numeric
defined_complexity + child_complexity
else
raise("Invalid complexity: #{defined_complexity.inspect} on #{path} (#{inspect})")
end
end
end
def complexity(new_complexity = nil)
case new_complexity
when Proc
if new_complexity.parameters.size != 3
fail(
"A complexity proc should always accept 3 parameters: ctx, args, child_complexity. "\
"E.g.: complexity ->(ctx, args, child_complexity) { child_complexity * args[:limit] }"
)
else
@complexity = new_complexity
end
when Numeric
@complexity = new_complexity
when nil
if @resolver_class
@complexity || @resolver_class.complexity || 1
else
@complexity || 1
end
else
raise("Invalid complexity: #{new_complexity.inspect} on #{@name}")
end
end
# @return [Boolean] True if this field's {#max_page_size} should override the schema default.
def has_max_page_size?
@has_max_page_size || (@resolver_class && @resolver_class.has_max_page_size?)
end
# @return [Integer, nil] Applied to connections if {#has_max_page_size?}
def max_page_size
@max_page_size || (@resolver_class && @resolver_class.max_page_size)
end
# @return [Boolean] True if this field's {#default_page_size} should override the schema default.
def has_default_page_size?
@has_default_page_size || (@resolver_class && @resolver_class.has_default_page_size?)
end
# @return [Integer, nil] Applied to connections if {#has_default_page_size?}
def default_page_size
@default_page_size || (@resolver_class && @resolver_class.default_page_size)
end
class MissingReturnTypeError < GraphQL::Error; end
attr_writer :type
def type
if @resolver_class
return_type = @return_type_expr || @resolver_class.type_expr
if return_type.nil?
raise MissingReturnTypeError, "Can't determine the return type for #{self.path} (it has `resolver: #{@resolver_class}`, perhaps that class is missing a `type ...` declaration, or perhaps its type causes a cyclical loading issue)"
end
nullable = @return_type_null.nil? ? @resolver_class.null : @return_type_null
Member::BuildType.parse_type(return_type, null: nullable)
else
@type ||= Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
end
rescue GraphQL::Schema::InvalidDocumentError, MissingReturnTypeError => err
# Let this propagate up
raise err
rescue StandardError => err
raise MissingReturnTypeError, "Failed to build return type for #{@owner.graphql_name}.#{name} from #{@return_type_expr.inspect}: (#{err.class}) #{err.message}", err.backtrace
end
def visible?(context)
if @resolver_class
@resolver_class.visible?(context)
else
true
end
end
def accessible?(context)
if @resolver_class
@resolver_class.accessible?(context)
else
true
end
end
def authorized?(object, args, context)
if @resolver_class
# The resolver _instance_ will check itself during `resolve()`
@resolver_class.authorized?(object, context)
else
if (arg_values = context[:current_arguments])
# ^^ that's provided by the interpreter at runtime, and includes info about whether the default value was used or not.
using_arg_values = true
arg_values = arg_values.argument_values
else
arg_values = args
using_arg_values = false
end
# Faster than `.any?`
arguments(context).each_value do |arg|
arg_key = arg.keyword
if arg_values.key?(arg_key)
arg_value = arg_values[arg_key]
if using_arg_values
if arg_value.default_used?
# pass -- no auth required for default used
next
else
application_arg_value = arg_value.value
if application_arg_value.is_a?(GraphQL::Execution::Interpreter::Arguments)
application_arg_value.keyword_arguments
end
end
else
application_arg_value = arg_value
end
if !arg.authorized?(object, application_arg_value, context)
return false
end
end
end
true
end
end
# This method is called by the interpreter for each field.
# You can extend it in your base field classes.
# @param object [GraphQL::Schema::Object] An instance of some type class, wrapping an application object
# @param args [Hash] A symbol-keyed hash of Ruby keyword arguments. (Empty if no args)
# @param ctx [GraphQL::Query::Context]
def resolve(object, args, query_ctx)
# Unwrap the GraphQL object to get the application object.
application_object = object.object
method_receiver = nil
method_to_call = nil
method_args = nil
Schema::Validator.validate!(validators, application_object, query_ctx, args)
query_ctx.schema.after_lazy(self.authorized?(application_object, args, query_ctx)) do |is_authorized|
if is_authorized
with_extensions(object, args, query_ctx) do |obj, ruby_kwargs|
method_args = ruby_kwargs
if @resolver_class
if obj.is_a?(GraphQL::Schema::Object)
obj = obj.object
end
obj = @resolver_class.new(object: obj, context: query_ctx, field: self)
end
inner_object = obj.object
if defined?(@hash_key)
hash_value = if inner_object.is_a?(Hash)
inner_object.key?(@hash_key) ? inner_object[@hash_key] : inner_object[@hash_key_str]
elsif inner_object.respond_to?(@hash_key)
inner_object.public_send(@hash_key)
else
nil
end
if hash_value == false
hash_value
else
hash_value || (@fallback_value != :not_given ? @fallback_value : nil)
end
elsif obj.respond_to?(resolver_method)
method_to_call = resolver_method
method_receiver = obj
# Call the method with kwargs, if there are any
if ruby_kwargs.any?
obj.public_send(resolver_method, **ruby_kwargs)
else
obj.public_send(resolver_method)
end
elsif inner_object.is_a?(Hash)
if @dig_keys
inner_object.dig(*@dig_keys)
elsif inner_object.key?(@method_sym)
inner_object[@method_sym]
elsif inner_object.key?(@method_str)
inner_object[@method_str]
elsif @fallback_value != :not_given
@fallback_value
else
nil
end
elsif inner_object.respond_to?(@method_sym)
method_to_call = @method_sym
method_receiver = obj.object
if ruby_kwargs.any?
inner_object.public_send(@method_sym, **ruby_kwargs)
else
inner_object.public_send(@method_sym)
end
elsif @fallback_value != :not_given
@fallback_value
else
raise <<-ERR
Failed to implement #{@owner.graphql_name}.#{@name}, tried:
- `#{obj.class}##{resolver_method}`, which did not exist
- `#{inner_object.class}##{@method_sym}`, which did not exist
- Looking up hash key `#{@method_sym.inspect}` or `#{@method_str.inspect}` on `#{inner_object}`, but it wasn't a Hash
To implement this field, define one of the methods above (and check for typos), or supply a `fallback_value`.
ERR
end
end
else
raise GraphQL::UnauthorizedFieldError.new(object: application_object, type: object.class, context: query_ctx, field: self)
end
end
rescue GraphQL::UnauthorizedFieldError => err
err.field ||= self
begin
query_ctx.schema.unauthorized_field(err)
rescue GraphQL::ExecutionError => err
err
end
rescue GraphQL::UnauthorizedError => err
begin
query_ctx.schema.unauthorized_object(err)
rescue GraphQL::ExecutionError => err
err
end
rescue ArgumentError
if method_receiver && method_to_call
assert_satisfactory_implementation(method_receiver, method_to_call, method_args)
end
# if the line above doesn't raise, re-raise
raise
end
# @param ctx [GraphQL::Query::Context]
def fetch_extra(extra_name, ctx)
if extra_name != :path && extra_name != :ast_node && respond_to?(extra_name)
self.public_send(extra_name)
elsif ctx.respond_to?(extra_name)
ctx.public_send(extra_name)
else
raise GraphQL::RequiredImplementationMissingError, "Unknown field extra for #{self.path}: #{extra_name.inspect}"
end
end
private
def assert_satisfactory_implementation(receiver, method_name, ruby_kwargs)
method_defn = receiver.method(method_name)
unsatisfied_ruby_kwargs = ruby_kwargs.dup
unsatisfied_method_params = []
encountered_keyrest = false
method_defn.parameters.each do |(param_type, param_name)|
case param_type
when :key
unsatisfied_ruby_kwargs.delete(param_name)
when :keyreq
if unsatisfied_ruby_kwargs.key?(param_name)
unsatisfied_ruby_kwargs.delete(param_name)
else
unsatisfied_method_params << "- `#{param_name}:` is required by Ruby, but not by GraphQL. Consider `#{param_name}: nil` instead, or making this argument required in GraphQL."
end
when :keyrest
encountered_keyrest = true
when :req
unsatisfied_method_params << "- `#{param_name}` is required by Ruby, but GraphQL doesn't pass positional arguments. If it's meant to be a GraphQL argument, use `#{param_name}:` instead. Otherwise, remove it."
when :opt, :rest
# This is fine, although it will never be present
end
end
if encountered_keyrest
unsatisfied_ruby_kwargs.clear
end
if unsatisfied_ruby_kwargs.any? || unsatisfied_method_params.any?
raise FieldImplementationFailed.new, <<-ERR
Failed to call `#{method_name.inspect}` on #{receiver.inspect} because the Ruby method params were incompatible with the GraphQL arguments:
#{ unsatisfied_ruby_kwargs
.map { |key, value| "- `#{key}: #{value}` was given by GraphQL but not defined in the Ruby method. Add `#{key}:` to the method parameters." }
.concat(unsatisfied_method_params)
.join("\n") }
ERR
end
end
# Wrap execution with hooks.
# Written iteratively to avoid big stack traces.
# @return [Object] Whatever the
def with_extensions(obj, args, ctx)
if @extensions.empty?
yield(obj, args)
else
# This is a hack to get the _last_ value for extended obj and args,
# in case one of the extensions doesn't `yield`.
# (There's another implementation that uses multiple-return, but I'm wary of the perf cost of the extra arrays)
extended = { args: args, obj: obj, memos: nil, added_extras: nil }
value = run_extensions_before_resolve(obj, args, ctx, extended) do |obj, args|
if (added_extras = extended[:added_extras])
args = args.dup
added_extras.each { |e| args.delete(e) }
end
yield(obj, args)
end
extended_obj = extended[:obj]
extended_args = extended[:args]
memos = extended[:memos] || EMPTY_HASH
ctx.schema.after_lazy(value) do |resolved_value|
idx = 0
@extensions.each do |ext|
memo = memos[idx]
# TODO after_lazy?
resolved_value = ext.after_resolve(object: extended_obj, arguments: extended_args, context: ctx, value: resolved_value, memo: memo)
idx += 1
end
resolved_value
end
end
end
def run_extensions_before_resolve(obj, args, ctx, extended, idx: 0)
extension = @extensions[idx]
if extension
extension.resolve(object: obj, arguments: args, context: ctx) do |extended_obj, extended_args, memo|
if memo
memos = extended[:memos] ||= {}
memos[idx] = memo
end
if (extras = extension.added_extras)
ae = extended[:added_extras] ||= []
ae.concat(extras)
end
extended[:obj] = extended_obj
extended[:args] = extended_args
run_extensions_before_resolve(extended_obj, extended_args, ctx, extended, idx: idx + 1) { |o, a| yield(o, a) }
end
else
yield(obj, args)
end
end
end
end
end
Update lib/graphql/schema/field.rb
Co-authored-by: Robert Mosolgo <5a5f0a28da4ab44930cf56ebe2125f3128869e52@gmail.com>
# frozen_string_literal: true
require "graphql/schema/field/connection_extension"
require "graphql/schema/field/scope_extension"
module GraphQL
class Schema
class Field
include GraphQL::Schema::Member::HasArguments
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasPath
include GraphQL::Schema::Member::HasValidators
extend GraphQL::Schema::FindInheritedValue
include GraphQL::Schema::FindInheritedValue::EmptyObjects
include GraphQL::Schema::Member::HasDirectives
include GraphQL::Schema::Member::HasDeprecationReason
class FieldImplementationFailed < GraphQL::Error; end
# @return [String] the GraphQL name for this field, camelized unless `camelize: false` is provided
attr_reader :name
alias :graphql_name :name
attr_writer :description
# @return [Symbol] Method or hash key on the underlying object to look up
attr_reader :method_sym
# @return [String] Method or hash key on the underlying object to look up
attr_reader :method_str
attr_reader :hash_key
attr_reader :dig_keys
# @return [Symbol] The method on the type to look up
def resolver_method
if @resolver_class
@resolver_class.resolver_method
else
@resolver_method
end
end
# @return [Class] The thing this field was defined on (type, mutation, resolver)
attr_accessor :owner
# @return [Class] The GraphQL type this field belongs to. (For fields defined on mutations, it's the payload type)
def owner_type
@owner_type ||= if owner.nil?
raise GraphQL::InvariantError, "Field #{original_name.inspect} (graphql name: #{graphql_name.inspect}) has no owner, but all fields should have an owner. How did this happen?!"
elsif owner < GraphQL::Schema::Mutation
owner.payload_type
else
owner
end
end
# @return [Symbol] the original name of the field, passed in by the user
attr_reader :original_name
# @return [Class, nil] The {Schema::Resolver} this field was derived from, if there is one
def resolver
@resolver_class
end
# @return [Boolean] Is this field a predefined introspection field?
def introspection?
@introspection
end
def inspect
"#<#{self.class} #{path}#{all_argument_definitions.any? ? "(...)" : ""}: #{type.to_type_signature}>"
end
alias :mutation :resolver
# @return [Boolean] Apply tracing to this field? (Default: skip scalars, this is the override value)
attr_reader :trace
# @return [String, nil]
def subscription_scope
@subscription_scope || (@resolver_class.respond_to?(:subscription_scope) ? @resolver_class.subscription_scope : nil)
end
attr_writer :subscription_scope
# Create a field instance from a list of arguments, keyword arguments, and a block.
#
# This method implements prioritization between the `resolver` or `mutation` defaults
# and the local overrides via other keywords.
#
# It also normalizes positional arguments into keywords for {Schema::Field#initialize}.
# @param resolver [Class] A {GraphQL::Schema::Resolver} class to use for field configuration
# @param mutation [Class] A {GraphQL::Schema::Mutation} class to use for field configuration
# @param subscription [Class] A {GraphQL::Schema::Subscription} class to use for field configuration
# @return [GraphQL::Schema:Field] an instance of `self
# @see {.initialize} for other options
def self.from_options(name = nil, type = nil, desc = nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
if (resolver_class = resolver || mutation || subscription)
# Add a reference to that parent class
kwargs[:resolver_class] = resolver_class
end
if name
kwargs[:name] = name
end
if !type.nil?
if desc
if kwargs[:description]
raise ArgumentError, "Provide description as a positional argument or `description:` keyword, but not both (#{desc.inspect}, #{kwargs[:description].inspect})"
end
kwargs[:description] = desc
kwargs[:type] = type
elsif (resolver || mutation) && type.is_a?(String)
# The return type should be copied from the resolver, and the second positional argument is the description
kwargs[:description] = type
else
kwargs[:type] = type
end
if type.is_a?(Class) && type < GraphQL::Schema::Mutation
raise ArgumentError, "Use `field #{name.inspect}, mutation: Mutation, ...` to provide a mutation to this field instead"
end
end
new(**kwargs, &block)
end
# Can be set with `connection: true|false` or inferred from a type name ending in `*Connection`
# @return [Boolean] if true, this field will be wrapped with Relay connection behavior
def connection?
if @connection.nil?
# Provide default based on type name
return_type_name = if @resolver_class && @resolver_class.type
Member::BuildType.to_type_name(@resolver_class.type)
elsif @return_type_expr
Member::BuildType.to_type_name(@return_type_expr)
else
# As a last ditch, try to force loading the return type:
type.unwrap.name
end
@connection = return_type_name.end_with?("Connection")
else
@connection
end
end
# @return [Boolean] if true, the return type's `.scope_items` method will be applied to this field's return value
def scoped?
if !@scope.nil?
# The default was overridden
@scope
elsif @return_type_expr
# Detect a list return type, but don't call `type` since that may eager-load an otherwise lazy-loaded type
@return_type_expr.is_a?(Array) ||
(@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) ||
connection?
elsif @resolver_class
resolver_type = @resolver_class.type_expr
resolver_type.is_a?(Array) ||
(resolver_type.is_a?(String) && resolver_type.include?("[")) ||
connection?
else
false
end
end
# This extension is applied to fields when {#connection?} is true.
#
# You can override it in your base field definition.
# @return [Class] A {FieldExtension} subclass for implementing pagination behavior.
# @example Configuring a custom extension
# class Types::BaseField < GraphQL::Schema::Field
# connection_extension(MyCustomExtension)
# end
def self.connection_extension(new_extension_class = nil)
if new_extension_class
@connection_extension = new_extension_class
else
@connection_extension ||= find_inherited_value(:connection_extension, ConnectionExtension)
end
end
# @return Boolean
attr_reader :relay_node_field
# @return Boolean
attr_reader :relay_nodes_field
# @return [Boolean] Should we warn if this field's name conflicts with a built-in method?
def method_conflict_warning?
@method_conflict_warning
end
# @param name [Symbol] The underscore-cased version of this field name (will be camelized for the GraphQL API)
# @param type [Class, GraphQL::BaseType, Array] The return type of this field
# @param owner [Class] The type that this field belongs to
# @param null [Boolean] (defaults to `true`) `true` if this field may return `null`, `false` if it is never `null`
# @param description [String] Field description
# @param deprecation_reason [String] If present, the field is marked "deprecated" with this message
# @param method [Symbol] The method to call on the underlying object to resolve this field (defaults to `name`)
# @param hash_key [String, Symbol] The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults to `name` or `name.to_s`)
# @param dig [Array<String, Symbol>] The nested hash keys to lookup on the underlying hash to resolve this field using dig
# @param resolver_method [Symbol] The method on the type to call to resolve this field (defaults to `name`)
# @param connection [Boolean] `true` if this field should get automagic connection behavior; default is to infer by `*Connection` in the return type name
# @param connection_extension [Class] The extension to add, to implement connections. If `nil`, no extension is added.
# @param max_page_size [Integer, nil] For connections, the maximum number of items to return from this field, or `nil` to allow unlimited results.
# @param default_page_size [Integer, nil] For connections, the default number of items to return from this field, or `nil` to return unlimited results.
# @param introspection [Boolean] If true, this field will be marked as `#introspection?` and the name may begin with `__`
# @param resolver_class [Class] (Private) A {Schema::Resolver} which this field was derived from. Use `resolver:` to create a field with a resolver.
# @param arguments [{String=>GraphQL::Schema::Argument, Hash}] Arguments for this field (may be added in the block, also)
# @param camelize [Boolean] If true, the field name will be camelized when building the schema
# @param complexity [Numeric] When provided, set the complexity for this field
# @param scope [Boolean] If true, the return type's `.scope_items` method will be called on the return value
# @param subscription_scope [Symbol, String] A key in `context` which will be used to scope subscription payloads
# @param extensions [Array<Class, Hash<Class => Object>>] Named extensions to apply to this field (see also {#extension})
# @param directives [Hash{Class => Hash}] Directives to apply to this field
# @param trace [Boolean] If true, a {GraphQL::Tracing} tracer will measure this scalar field
# @param broadcastable [Boolean] Whether or not this field can be distributed in subscription broadcasts
# @param ast_node [Language::Nodes::FieldDefinition, nil] If this schema was parsed from definition, this AST node defined the field
# @param method_conflict_warning [Boolean] If false, skip the warning if this field's method conflicts with a built-in method
# @param validates [Array<Hash>] Configurations for validating this field
# @fallback_value [Object] A fallback value if the method is not defined
def initialize(type: nil, name: nil, owner: nil, null: nil, description: :not_given, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: :not_given, default_page_size: :not_given, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, ast_node: nil, extras: EMPTY_ARRAY, extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, broadcastable: nil, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, fallback_value: :not_given, &definition_block)
if name.nil?
raise ArgumentError, "missing first `name` argument or keyword `name:`"
end
if !(resolver_class)
if type.nil?
raise ArgumentError, "missing second `type` argument or keyword `type:`"
end
end
@original_name = name
name_s = -name.to_s
@underscored_name = -Member::BuildType.underscore(name_s)
@name = -(camelize ? Member::BuildType.camelize(name_s) : name_s)
if description != :not_given
@description = description
end
self.deprecation_reason = deprecation_reason
if method && hash_key && dig
raise ArgumentError, "Provide `method:`, `hash_key:` _or_ `dig:`, not multiple. (called with: `method: #{method.inspect}, hash_key: #{hash_key.inspect}, dig: #{dig.inspect}`)"
end
if resolver_method
if method
raise ArgumentError, "Provide `method:` _or_ `resolver_method:`, not both. (called with: `method: #{method.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
if hash_key || dig
raise ArgumentError, "Provide `hash_key:`, `dig:`, _or_ `resolver_method:`, not multiple. (called with: `hash_key: #{hash_key.inspect}, dig: #{dig.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
end
method_name = method || hash_key || name_s
@dig_keys = dig
if hash_key
@hash_key = hash_key.to_sym
@hash_key_str = hash_key.to_s
end
@method_str = -method_name.to_s
@method_sym = method_name.to_sym
@resolver_method = (resolver_method || name_s).to_sym
@complexity = complexity
@return_type_expr = type
@return_type_null = if !null.nil?
null
elsif resolver_class
nil
else
true
end
@connection = connection
@has_max_page_size = max_page_size != :not_given
@max_page_size = max_page_size == :not_given ? nil : max_page_size
@has_default_page_size = default_page_size != :not_given
@default_page_size = default_page_size == :not_given ? nil : default_page_size
@introspection = introspection
@extras = extras
if !broadcastable.nil?
@broadcastable = broadcastable
end
@resolver_class = resolver_class
@scope = scope
@trace = trace
@relay_node_field = relay_node_field
@relay_nodes_field = relay_nodes_field
@ast_node = ast_node
@method_conflict_warning = method_conflict_warning
@fallback_value = fallback_value
arguments.each do |name, arg|
case arg
when Hash
argument(name: name, **arg)
when GraphQL::Schema::Argument
add_argument(arg)
when Array
arg.each { |a| add_argument(a) }
else
raise ArgumentError, "Unexpected argument config (#{arg.class}): #{arg.inspect}"
end
end
@owner = owner
@subscription_scope = subscription_scope
@extensions = EMPTY_ARRAY
@call_after_define = false
# This should run before connection extension,
# but should it run after the definition block?
if scoped?
self.extension(ScopeExtension)
end
# The problem with putting this after the definition_block
# is that it would override arguments
if connection? && connection_extension
self.extension(connection_extension)
end
# Do this last so we have as much context as possible when initializing them:
if extensions.any?
self.extensions(extensions)
end
if resolver_class && resolver_class.extensions.any?
self.extensions(resolver_class.extensions)
end
if directives.any?
directives.each do |(dir_class, options)|
self.directive(dir_class, **options)
end
end
if !validates.empty?
self.validates(validates)
end
if definition_block
if definition_block.arity == 1
yield self
else
instance_eval(&definition_block)
end
end
self.extensions.each(&:after_define_apply)
@call_after_define = true
end
# If true, subscription updates with this field can be shared between viewers
# @return [Boolean, nil]
# @see GraphQL::Subscriptions::BroadcastAnalyzer
def broadcastable?
if defined?(@broadcastable)
@broadcastable
elsif @resolver_class
@resolver_class.broadcastable?
else
nil
end
end
# @param text [String]
# @return [String]
def description(text = nil)
if text
@description = text
elsif defined?(@description)
@description
elsif @resolver_class
@description || @resolver_class.description
else
nil
end
end
# Read extension instances from this field,
# or add new classes/options to be initialized on this field.
# Extensions are executed in the order they are added.
#
# @example adding an extension
# extensions([MyExtensionClass])
#
# @example adding multiple extensions
# extensions([MyExtensionClass, AnotherExtensionClass])
#
# @example adding an extension with options
# extensions([MyExtensionClass, { AnotherExtensionClass => { filter: true } }])
#
# @param extensions [Array<Class, Hash<Class => Hash>>] Add extensions to this field. For hash elements, only the first key/value is used.
# @return [Array<GraphQL::Schema::FieldExtension>] extensions to apply to this field
def extensions(new_extensions = nil)
if new_extensions
new_extensions.each do |extension_config|
if extension_config.is_a?(Hash)
extension_class, options = *extension_config.to_a[0]
self.extension(extension_class, options)
else
self.extension(extension_config)
end
end
end
@extensions
end
# Add `extension` to this field, initialized with `options` if provided.
#
# @example adding an extension
# extension(MyExtensionClass)
#
# @example adding an extension with options
# extension(MyExtensionClass, filter: true)
#
# @param extension_class [Class] subclass of {Schema::FieldExtension}
# @param options [Hash] if provided, given as `options:` when initializing `extension`.
# @return [void]
def extension(extension_class, options = nil)
extension_inst = extension_class.new(field: self, options: options)
if @extensions.frozen?
@extensions = @extensions.dup
end
if @call_after_define
extension_inst.after_define_apply
end
@extensions << extension_inst
nil
end
# Read extras (as symbols) from this field,
# or add new extras to be opted into by this field's resolver.
#
# @param new_extras [Array<Symbol>] Add extras to this field
# @return [Array<Symbol>]
def extras(new_extras = nil)
if new_extras.nil?
# Read the value
field_extras = @extras
if @resolver_class && @resolver_class.extras.any?
field_extras + @resolver_class.extras
else
field_extras
end
else
if @extras.frozen?
@extras = @extras.dup
end
# Append to the set of extras on this field
@extras.concat(new_extras)
end
end
def calculate_complexity(query:, nodes:, child_complexity:)
if respond_to?(:complexity_for)
lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
complexity_for(child_complexity: child_complexity, query: query, lookahead: lookahead)
elsif connection?
arguments = query.arguments_for(nodes.first, self)
max_possible_page_size = nil
if arguments.respond_to?(:[]) # It might have been an error
if arguments[:first]
max_possible_page_size = arguments[:first]
end
if arguments[:last] && (max_possible_page_size.nil? || arguments[:last] > max_possible_page_size)
max_possible_page_size = arguments[:last]
end
end
if max_possible_page_size.nil?
max_possible_page_size = default_page_size || query.schema.default_page_size || max_page_size || query.schema.default_max_page_size
end
if max_possible_page_size.nil?
raise GraphQL::Error, "Can't calculate complexity for #{path}, no `first:`, `last:`, `default_page_size`, `max_page_size` or `default_max_page_size`"
else
metadata_complexity = 0
lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
if (page_info_lookahead = lookahead.selection(:page_info)).selected?
metadata_complexity += 1 # pageInfo
metadata_complexity += page_info_lookahead.selections.size # subfields
end
if lookahead.selects?(:total) || lookahead.selects?(:total_count) || lookahead.selects?(:count)
metadata_complexity += 1
end
nodes_edges_complexity = 0
nodes_edges_complexity += 1 if lookahead.selects?(:edges)
nodes_edges_complexity += 1 if lookahead.selects?(:nodes)
# Possible bug: selections on `edges` and `nodes` are _both_ multiplied here. Should they be?
items_complexity = child_complexity - metadata_complexity - nodes_edges_complexity
# Add 1 for _this_ field
1 + (max_possible_page_size * items_complexity) + metadata_complexity + nodes_edges_complexity
end
else
defined_complexity = complexity
case defined_complexity
when Proc
arguments = query.arguments_for(nodes.first, self)
if arguments.is_a?(GraphQL::ExecutionError)
return child_complexity
elsif arguments.respond_to?(:keyword_arguments)
arguments = arguments.keyword_arguments
end
defined_complexity.call(query.context, arguments, child_complexity)
when Numeric
defined_complexity + child_complexity
else
raise("Invalid complexity: #{defined_complexity.inspect} on #{path} (#{inspect})")
end
end
end
def complexity(new_complexity = nil)
case new_complexity
when Proc
if new_complexity.parameters.size != 3
fail(
"A complexity proc should always accept 3 parameters: ctx, args, child_complexity. "\
"E.g.: complexity ->(ctx, args, child_complexity) { child_complexity * args[:limit] }"
)
else
@complexity = new_complexity
end
when Numeric
@complexity = new_complexity
when nil
if @resolver_class
@complexity || @resolver_class.complexity || 1
else
@complexity || 1
end
else
raise("Invalid complexity: #{new_complexity.inspect} on #{@name}")
end
end
# @return [Boolean] True if this field's {#max_page_size} should override the schema default.
def has_max_page_size?
@has_max_page_size || (@resolver_class && @resolver_class.has_max_page_size?)
end
# @return [Integer, nil] Applied to connections if {#has_max_page_size?}
def max_page_size
@max_page_size || (@resolver_class && @resolver_class.max_page_size)
end
# @return [Boolean] True if this field's {#default_page_size} should override the schema default.
def has_default_page_size?
@has_default_page_size || (@resolver_class && @resolver_class.has_default_page_size?)
end
# @return [Integer, nil] Applied to connections if {#has_default_page_size?}
def default_page_size
@default_page_size || (@resolver_class && @resolver_class.default_page_size)
end
class MissingReturnTypeError < GraphQL::Error; end
attr_writer :type
def type
if @resolver_class
return_type = @return_type_expr || @resolver_class.type_expr
if return_type.nil?
raise MissingReturnTypeError, "Can't determine the return type for #{self.path} (it has `resolver: #{@resolver_class}`, perhaps that class is missing a `type ...` declaration, or perhaps its type causes a cyclical loading issue)"
end
nullable = @return_type_null.nil? ? @resolver_class.null : @return_type_null
Member::BuildType.parse_type(return_type, null: nullable)
else
@type ||= Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
end
rescue GraphQL::Schema::InvalidDocumentError, MissingReturnTypeError => err
# Let this propagate up
raise err
rescue StandardError => err
raise MissingReturnTypeError, "Failed to build return type for #{@owner.graphql_name}.#{name} from #{@return_type_expr.inspect}: (#{err.class}) #{err.message}", err.backtrace
end
def visible?(context)
if @resolver_class
@resolver_class.visible?(context)
else
true
end
end
def accessible?(context)
if @resolver_class
@resolver_class.accessible?(context)
else
true
end
end
def authorized?(object, args, context)
if @resolver_class
# The resolver _instance_ will check itself during `resolve()`
@resolver_class.authorized?(object, context)
else
if (arg_values = context[:current_arguments])
# ^^ that's provided by the interpreter at runtime, and includes info about whether the default value was used or not.
using_arg_values = true
arg_values = arg_values.argument_values
else
arg_values = args
using_arg_values = false
end
# Faster than `.any?`
arguments(context).each_value do |arg|
arg_key = arg.keyword
if arg_values.key?(arg_key)
arg_value = arg_values[arg_key]
if using_arg_values
if arg_value.default_used?
# pass -- no auth required for default used
next
else
application_arg_value = arg_value.value
if application_arg_value.is_a?(GraphQL::Execution::Interpreter::Arguments)
application_arg_value.keyword_arguments
end
end
else
application_arg_value = arg_value
end
if !arg.authorized?(object, application_arg_value, context)
return false
end
end
end
true
end
end
# This method is called by the interpreter for each field.
# You can extend it in your base field classes.
# @param object [GraphQL::Schema::Object] An instance of some type class, wrapping an application object
# @param args [Hash] A symbol-keyed hash of Ruby keyword arguments. (Empty if no args)
# @param ctx [GraphQL::Query::Context]
def resolve(object, args, query_ctx)
# Unwrap the GraphQL object to get the application object.
application_object = object.object
method_receiver = nil
method_to_call = nil
method_args = nil
Schema::Validator.validate!(validators, application_object, query_ctx, args)
query_ctx.schema.after_lazy(self.authorized?(application_object, args, query_ctx)) do |is_authorized|
if is_authorized
with_extensions(object, args, query_ctx) do |obj, ruby_kwargs|
method_args = ruby_kwargs
if @resolver_class
if obj.is_a?(GraphQL::Schema::Object)
obj = obj.object
end
obj = @resolver_class.new(object: obj, context: query_ctx, field: self)
end
inner_object = obj.object
if defined?(@hash_key)
hash_value = if inner_object.is_a?(Hash)
inner_object.key?(@hash_key) ? inner_object[@hash_key] : inner_object[@hash_key_str]
elsif inner_object.respond_to?(:[])
inner_object[@hash_key]
else
nil
end
if hash_value == false
hash_value
else
hash_value || (@fallback_value != :not_given ? @fallback_value : nil)
end
elsif obj.respond_to?(resolver_method)
method_to_call = resolver_method
method_receiver = obj
# Call the method with kwargs, if there are any
if ruby_kwargs.any?
obj.public_send(resolver_method, **ruby_kwargs)
else
obj.public_send(resolver_method)
end
elsif inner_object.is_a?(Hash)
if @dig_keys
inner_object.dig(*@dig_keys)
elsif inner_object.key?(@method_sym)
inner_object[@method_sym]
elsif inner_object.key?(@method_str)
inner_object[@method_str]
elsif @fallback_value != :not_given
@fallback_value
else
nil
end
elsif inner_object.respond_to?(@method_sym)
method_to_call = @method_sym
method_receiver = obj.object
if ruby_kwargs.any?
inner_object.public_send(@method_sym, **ruby_kwargs)
else
inner_object.public_send(@method_sym)
end
elsif @fallback_value != :not_given
@fallback_value
else
raise <<-ERR
Failed to implement #{@owner.graphql_name}.#{@name}, tried:
- `#{obj.class}##{resolver_method}`, which did not exist
- `#{inner_object.class}##{@method_sym}`, which did not exist
- Looking up hash key `#{@method_sym.inspect}` or `#{@method_str.inspect}` on `#{inner_object}`, but it wasn't a Hash
To implement this field, define one of the methods above (and check for typos), or supply a `fallback_value`.
ERR
end
end
else
raise GraphQL::UnauthorizedFieldError.new(object: application_object, type: object.class, context: query_ctx, field: self)
end
end
rescue GraphQL::UnauthorizedFieldError => err
err.field ||= self
begin
query_ctx.schema.unauthorized_field(err)
rescue GraphQL::ExecutionError => err
err
end
rescue GraphQL::UnauthorizedError => err
begin
query_ctx.schema.unauthorized_object(err)
rescue GraphQL::ExecutionError => err
err
end
rescue ArgumentError
if method_receiver && method_to_call
assert_satisfactory_implementation(method_receiver, method_to_call, method_args)
end
# if the line above doesn't raise, re-raise
raise
end
# @param ctx [GraphQL::Query::Context]
def fetch_extra(extra_name, ctx)
if extra_name != :path && extra_name != :ast_node && respond_to?(extra_name)
self.public_send(extra_name)
elsif ctx.respond_to?(extra_name)
ctx.public_send(extra_name)
else
raise GraphQL::RequiredImplementationMissingError, "Unknown field extra for #{self.path}: #{extra_name.inspect}"
end
end
private
def assert_satisfactory_implementation(receiver, method_name, ruby_kwargs)
method_defn = receiver.method(method_name)
unsatisfied_ruby_kwargs = ruby_kwargs.dup
unsatisfied_method_params = []
encountered_keyrest = false
method_defn.parameters.each do |(param_type, param_name)|
case param_type
when :key
unsatisfied_ruby_kwargs.delete(param_name)
when :keyreq
if unsatisfied_ruby_kwargs.key?(param_name)
unsatisfied_ruby_kwargs.delete(param_name)
else
unsatisfied_method_params << "- `#{param_name}:` is required by Ruby, but not by GraphQL. Consider `#{param_name}: nil` instead, or making this argument required in GraphQL."
end
when :keyrest
encountered_keyrest = true
when :req
unsatisfied_method_params << "- `#{param_name}` is required by Ruby, but GraphQL doesn't pass positional arguments. If it's meant to be a GraphQL argument, use `#{param_name}:` instead. Otherwise, remove it."
when :opt, :rest
# This is fine, although it will never be present
end
end
if encountered_keyrest
unsatisfied_ruby_kwargs.clear
end
if unsatisfied_ruby_kwargs.any? || unsatisfied_method_params.any?
raise FieldImplementationFailed.new, <<-ERR
Failed to call `#{method_name.inspect}` on #{receiver.inspect} because the Ruby method params were incompatible with the GraphQL arguments:
#{ unsatisfied_ruby_kwargs
.map { |key, value| "- `#{key}: #{value}` was given by GraphQL but not defined in the Ruby method. Add `#{key}:` to the method parameters." }
.concat(unsatisfied_method_params)
.join("\n") }
ERR
end
end
# Wrap execution with hooks.
# Written iteratively to avoid big stack traces.
# @return [Object] Whatever the
def with_extensions(obj, args, ctx)
if @extensions.empty?
yield(obj, args)
else
# This is a hack to get the _last_ value for extended obj and args,
# in case one of the extensions doesn't `yield`.
# (There's another implementation that uses multiple-return, but I'm wary of the perf cost of the extra arrays)
extended = { args: args, obj: obj, memos: nil, added_extras: nil }
value = run_extensions_before_resolve(obj, args, ctx, extended) do |obj, args|
if (added_extras = extended[:added_extras])
args = args.dup
added_extras.each { |e| args.delete(e) }
end
yield(obj, args)
end
extended_obj = extended[:obj]
extended_args = extended[:args]
memos = extended[:memos] || EMPTY_HASH
ctx.schema.after_lazy(value) do |resolved_value|
idx = 0
@extensions.each do |ext|
memo = memos[idx]
# TODO after_lazy?
resolved_value = ext.after_resolve(object: extended_obj, arguments: extended_args, context: ctx, value: resolved_value, memo: memo)
idx += 1
end
resolved_value
end
end
end
def run_extensions_before_resolve(obj, args, ctx, extended, idx: 0)
extension = @extensions[idx]
if extension
extension.resolve(object: obj, arguments: args, context: ctx) do |extended_obj, extended_args, memo|
if memo
memos = extended[:memos] ||= {}
memos[idx] = memo
end
if (extras = extension.added_extras)
ae = extended[:added_extras] ||= []
ae.concat(extras)
end
extended[:obj] = extended_obj
extended[:args] = extended_args
run_extensions_before_resolve(extended_obj, extended_args, ctx, extended, idx: idx + 1) { |o, a| yield(o, a) }
end
else
yield(obj, args)
end
end
end
end
end
|
# frozen_string_literal: true
# test_via: ../object.rb
require "graphql/schema/field/connection_extension"
require "graphql/schema/field/scope_extension"
module GraphQL
class Schema
class Field
if !String.method_defined?(:-@)
using GraphQL::StringDedupBackport
end
include GraphQL::Schema::Member::CachedGraphQLDefinition
include GraphQL::Schema::Member::AcceptsDefinition
include GraphQL::Schema::Member::HasArguments
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasPath
extend GraphQL::Schema::FindInheritedValue
include GraphQL::Schema::FindInheritedValue::EmptyObjects
# @return [String] the GraphQL name for this field, camelized unless `camelize: false` is provided
attr_reader :name
alias :graphql_name :name
attr_writer :description
# @return [String, nil] If present, the field is marked as deprecated with this documentation
attr_accessor :deprecation_reason
# @return [Symbol] Method or hash key on the underlying object to look up
attr_reader :method_sym
# @return [String] Method or hash key on the underlying object to look up
attr_reader :method_str
# @return [Symbol] The method on the type to look up
attr_reader :resolver_method
# @return [Class] The type that this field belongs to
attr_accessor :owner
# @return [Symbol] the original name of the field, passed in by the user
attr_reader :original_name
# @return [Class, nil] The {Schema::Resolver} this field was derived from, if there is one
def resolver
@resolver_class
end
alias :mutation :resolver
# @return [Boolean] Apply tracing to this field? (Default: skip scalars, this is the override value)
attr_reader :trace
# @return [String, nil]
attr_accessor :subscription_scope
# Create a field instance from a list of arguments, keyword arguments, and a block.
#
# This method implements prioritization between the `resolver` or `mutation` defaults
# and the local overrides via other keywords.
#
# It also normalizes positional arguments into keywords for {Schema::Field#initialize}.
# @param resolver [Class] A {GraphQL::Schema::Resolver} class to use for field configuration
# @param mutation [Class] A {GraphQL::Schema::Mutation} class to use for field configuration
# @param subscription [Class] A {GraphQL::Schema::Subscription} class to use for field configuration
# @return [GraphQL::Schema:Field] an instance of `self
# @see {.initialize} for other options
def self.from_options(name = nil, type = nil, desc = nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
if kwargs[:field]
if kwargs[:field] == GraphQL::Relay::Node.field
warn("Legacy-style `GraphQL::Relay::Node.field` is being added to a class-based type. See `GraphQL::Types::Relay::NodeField` for a replacement.")
return GraphQL::Types::Relay::NodeField
elsif kwargs[:field] == GraphQL::Relay::Node.plural_field
warn("Legacy-style `GraphQL::Relay::Node.plural_field` is being added to a class-based type. See `GraphQL::Types::Relay::NodesField` for a replacement.")
return GraphQL::Types::Relay::NodesField
end
end
if (parent_config = resolver || mutation || subscription)
# Get the parent config, merge in local overrides
kwargs = parent_config.field_options.merge(kwargs)
# Add a reference to that parent class
kwargs[:resolver_class] = parent_config
end
if name
kwargs[:name] = name
end
if !type.nil?
if type.is_a?(GraphQL::Field)
raise ArgumentError, "A GraphQL::Field was passed as the second argument, use the `field:` keyword for this instead."
end
if desc
if kwargs[:description]
raise ArgumentError, "Provide description as a positional argument or `description:` keyword, but not both (#{desc.inspect}, #{kwargs[:description].inspect})"
end
kwargs[:description] = desc
kwargs[:type] = type
elsif (kwargs[:field] || kwargs[:function] || resolver || mutation) && type.is_a?(String)
# The return type should be copied from `field` or `function`, and the second positional argument is the description
kwargs[:description] = type
else
kwargs[:type] = type
end
end
new(**kwargs, &block)
end
# Can be set with `connection: true|false` or inferred from a type name ending in `*Connection`
# @return [Boolean] if true, this field will be wrapped with Relay connection behavior
def connection?
if @connection.nil?
# Provide default based on type name
return_type_name = if (contains_type = @field || @function)
Member::BuildType.to_type_name(contains_type.type)
elsif @return_type_expr
Member::BuildType.to_type_name(@return_type_expr)
else
# As a last ditch, try to force loading the return type:
type.unwrap.name
end
@connection = return_type_name.end_with?("Connection")
else
@connection
end
end
# @return [Boolean] if true, the return type's `.scope_items` method will be applied to this field's return value
def scoped?
if !@scope.nil?
# The default was overridden
@scope
else
@return_type_expr && (@return_type_expr.is_a?(Array) || (@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) || connection?)
end
end
# This extension is applied to fields when {#connection?} is true.
#
# You can override it in your base field definition.
# @return [Class] A {FieldExtension} subclass for implementing pagination behavior.
# @example Configuring a custom extension
# class Types::BaseField < GraphQL::Schema::Field
# connection_extension(MyCustomExtension)
# end
def self.connection_extension(new_extension_class = nil)
if new_extension_class
@connection_extension = new_extension_class
else
@connection_extension ||= find_inherited_value(:connection_extension, ConnectionExtension)
end
end
# @return Boolean
attr_reader :relay_node_field
# @return [Boolean] Should we warn if this field's name conflicts with a built-in method?
def method_conflict_warning?
@method_conflict_warning
end
# @param name [Symbol] The underscore-cased version of this field name (will be camelized for the GraphQL API)
# @param type [Class, GraphQL::BaseType, Array] The return type of this field
# @param owner [Class] The type that this field belongs to
# @param null [Boolean] `true` if this field may return `null`, `false` if it is never `null`
# @param description [String] Field description
# @param deprecation_reason [String] If present, the field is marked "deprecated" with this message
# @param method [Symbol] The method to call on the underlying object to resolve this field (defaults to `name`)
# @param hash_key [String, Symbol] The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults to `name` or `name.to_s`)
# @param resolver_method [Symbol] The method on the type to call to resolve this field (defaults to `name`)
# @param connection [Boolean] `true` if this field should get automagic connection behavior; default is to infer by `*Connection` in the return type name
# @param connection_extension [Class] The extension to add, to implement connections. If `nil`, no extension is added.
# @param max_page_size [Integer, nil] For connections, the maximum number of items to return from this field, or `nil` to allow unlimited results.
# @param introspection [Boolean] If true, this field will be marked as `#introspection?` and the name may begin with `__`
# @param resolve [<#call(obj, args, ctx)>] **deprecated** for compatibility with <1.8.0
# @param field [GraphQL::Field, GraphQL::Schema::Field] **deprecated** for compatibility with <1.8.0
# @param function [GraphQL::Function] **deprecated** for compatibility with <1.8.0
# @param resolver_class [Class] (Private) A {Schema::Resolver} which this field was derived from. Use `resolver:` to create a field with a resolver.
# @param arguments [{String=>GraphQL::Schema::Argument, Hash}] Arguments for this field (may be added in the block, also)
# @param camelize [Boolean] If true, the field name will be camelized when building the schema
# @param complexity [Numeric] When provided, set the complexity for this field
# @param scope [Boolean] If true, the return type's `.scope_items` method will be called on the return value
# @param subscription_scope [Symbol, String] A key in `context` which will be used to scope subscription payloads
# @param extensions [Array<Class, Hash<Class => Object>>] Named extensions to apply to this field (see also {#extension})
# @param trace [Boolean] If true, a {GraphQL::Tracing} tracer will measure this scalar field
# @param ast_node [Language::Nodes::FieldDefinition, nil] If this schema was parsed from definition, this AST node defined the field
# @param method_conflict_warning [Boolean] If false, skip the warning if this field's method conflicts with a built-in method
def initialize(type: nil, name: nil, owner: nil, null: nil, field: nil, function: nil, description: nil, deprecation_reason: nil, method: nil, hash_key: nil, resolver_method: nil, resolve: nil, connection: nil, max_page_size: :not_given, scope: nil, introspection: false, camelize: true, trace: nil, complexity: 1, ast_node: nil, extras: [], extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, arguments: EMPTY_HASH, &definition_block)
if name.nil?
raise ArgumentError, "missing first `name` argument or keyword `name:`"
end
if !(field || function || resolver_class)
if type.nil?
raise ArgumentError, "missing second `type` argument or keyword `type:`"
end
if null.nil?
raise ArgumentError, "missing keyword argument null:"
end
end
if (field || function || resolve) && extras.any?
raise ArgumentError, "keyword `extras:` may only be used with method-based resolve and class-based field such as mutation class, please remove `field:`, `function:` or `resolve:`"
end
@original_name = name
name_s = -name.to_s
@underscored_name = -Member::BuildType.underscore(name_s)
@name = -(camelize ? Member::BuildType.camelize(name_s) : name_s)
@description = description
if field.is_a?(GraphQL::Schema::Field)
raise ArgumentError, "Instead of passing a field as `field:`, use `add_field(field)` to add an already-defined field."
else
@field = field
end
@function = function
@resolve = resolve
@deprecation_reason = deprecation_reason
if method && hash_key
raise ArgumentError, "Provide `method:` _or_ `hash_key:`, not both. (called with: `method: #{method.inspect}, hash_key: #{hash_key.inspect}`)"
end
if resolver_method
if method
raise ArgumentError, "Provide `method:` _or_ `resolver_method:`, not both. (called with: `method: #{method.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
if hash_key
raise ArgumentError, "Provide `hash_key:` _or_ `resolver_method:`, not both. (called with: `hash_key: #{hash_key.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
end
# TODO: I think non-string/symbol hash keys are wrongly normalized (eg `1` will not work)
method_name = method || hash_key || @underscored_name
resolver_method ||= @underscored_name.to_sym
@method_str = method_name.to_s
@method_sym = method_name.to_sym
@resolver_method = resolver_method
@complexity = complexity
@return_type_expr = type
@return_type_null = null
@connection = connection
@has_max_page_size = max_page_size != :not_given
@max_page_size = max_page_size
@introspection = introspection
@extras = extras
@resolver_class = resolver_class
@scope = scope
@trace = trace
@relay_node_field = relay_node_field
@relay_nodes_field = relay_nodes_field
@ast_node = ast_node
@method_conflict_warning = method_conflict_warning
arguments.each do |name, arg|
if arg.is_a?(Hash)
argument(name: name, **arg)
else
own_arguments[name] = arg
end
end
@owner = owner
@subscription_scope = subscription_scope
# Do this last so we have as much context as possible when initializing them:
@extensions = []
if extensions.any?
self.extensions(extensions)
end
# This should run before connection extension,
# but should it run after the definition block?
if scoped?
self.extension(ScopeExtension)
end
# The problem with putting this after the definition_block
# is that it would override arguments
if connection? && connection_extension
self.extension(connection_extension)
end
if definition_block
if definition_block.arity == 1
yield self
else
instance_eval(&definition_block)
end
end
end
# @param text [String]
# @return [String]
def description(text = nil)
if text
@description = text
else
@description
end
end
# Read extension instances from this field,
# or add new classes/options to be initialized on this field.
# Extensions are executed in the order they are added.
#
# @example adding an extension
# extensions([MyExtensionClass])
#
# @example adding multiple extensions
# extensions([MyExtensionClass, AnotherExtensionClass])
#
# @example adding an extension with options
# extensions([MyExtensionClass, { AnotherExtensionClass => { filter: true } }])
#
# @param extensions [Array<Class, Hash<Class => Object>>] Add extensions to this field. For hash elements, only the first key/value is used.
# @return [Array<GraphQL::Schema::FieldExtension>] extensions to apply to this field
def extensions(new_extensions = nil)
if new_extensions.nil?
# Read the value
@extensions
else
new_extensions.each do |extension|
if extension.is_a?(Hash)
extension = extension.to_a[0]
extension_class, options = *extension
@extensions << extension_class.new(field: self, options: options)
else
extension_class = extension
@extensions << extension_class.new(field: self, options: nil)
end
end
end
end
# Add `extension` to this field, initialized with `options` if provided.
#
# @example adding an extension
# extension(MyExtensionClass)
#
# @example adding an extension with options
# extension(MyExtensionClass, filter: true)
#
# @param extension [Class] subclass of {Schema::Fieldextension}
# @param options [Object] if provided, given as `options:` when initializing `extension`.
def extension(extension, options = nil)
extensions([{extension => options}])
end
# Read extras (as symbols) from this field,
# or add new extras to be opted into by this field's resolver.
#
# @param new_extras [Array<Symbol>] Add extras to this field
# @return [Array<Symbol>]
def extras(new_extras = nil)
if new_extras.nil?
# Read the value
@extras
else
# Append to the set of extras on this field
@extras.concat(new_extras)
end
end
def complexity(new_complexity = nil)
case new_complexity
when Proc
if new_complexity.parameters.size != 3
fail(
"A complexity proc should always accept 3 parameters: ctx, args, child_complexity. "\
"E.g.: complexity ->(ctx, args, child_complexity) { child_complexity * args[:limit] }"
)
else
@complexity = new_complexity
end
when Numeric
@complexity = new_complexity
when nil
@complexity
else
raise("Invalid complexity: #{new_complexity.inspect} on #{@name}")
end
end
# @return [Boolean] True if this field's {#max_page_size} should override the schema default.
def has_max_page_size?
@has_max_page_size
end
# @return [Integer, nil] Applied to connections if present
attr_reader :max_page_size
# @return [GraphQL::Field]
def to_graphql
field_defn = if @field
@field.dup
elsif @function
GraphQL::Function.build_field(@function)
else
GraphQL::Field.new
end
field_defn.name = @name
if @return_type_expr
field_defn.type = -> { type }
end
if @description
field_defn.description = @description
end
if @deprecation_reason
field_defn.deprecation_reason = @deprecation_reason
end
if @resolver_class
if @resolver_class < GraphQL::Schema::Mutation
field_defn.mutation = @resolver_class
end
field_defn.metadata[:resolver] = @resolver_class
end
if !@trace.nil?
field_defn.trace = @trace
end
if @relay_node_field
field_defn.relay_node_field = @relay_node_field
end
if @relay_nodes_field
field_defn.relay_nodes_field = @relay_nodes_field
end
field_defn.resolve = self.method(:resolve_field)
field_defn.connection = connection?
field_defn.connection_max_page_size = max_page_size
field_defn.introspection = @introspection
field_defn.complexity = @complexity
field_defn.subscription_scope = @subscription_scope
field_defn.ast_node = ast_node
arguments.each do |name, defn|
arg_graphql = defn.to_graphql
field_defn.arguments[arg_graphql.name] = arg_graphql
end
# Support a passed-in proc, one way or another
@resolve_proc = if @resolve
@resolve
elsif @function
@function
elsif @field
@field.resolve_proc
end
# Ok, `self` isn't a class, but this is for consistency with the classes
field_defn.metadata[:type_class] = self
field_defn.arguments_class = GraphQL::Query::Arguments.construct_arguments_class(field_defn)
field_defn
end
attr_writer :type
def type
@type ||= if @function
Member::BuildType.parse_type(@function.type, null: false)
elsif @field
Member::BuildType.parse_type(@field.type, null: false)
else
Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
end
rescue GraphQL::Schema::InvalidDocumentError => err
# Let this propagate up
raise err
rescue StandardError => err
raise ArgumentError, "Failed to build return type for #{@owner.graphql_name}.#{name} from #{@return_type_expr.inspect}: (#{err.class}) #{err.message}", err.backtrace
end
def visible?(context)
if @resolver_class
@resolver_class.visible?(context)
else
true
end
end
def accessible?(context)
if @resolver_class
@resolver_class.accessible?(context)
else
true
end
end
def authorized?(object, args, context)
if @resolver_class
# The resolver will check itself during `resolve()`
@resolver_class.authorized?(object, context)
else
# Faster than `.any?`
arguments.each_value do |arg|
if args.key?(arg.keyword) && !arg.authorized?(object, args[arg.keyword], context)
return false
end
end
true
end
end
# Implement {GraphQL::Field}'s resolve API.
#
# Eventually, we might hook up field instances to execution in another way. TBD.
# @see #resolve for how the interpreter hooks up to it
def resolve_field(obj, args, ctx)
ctx.schema.after_lazy(obj) do |after_obj|
# First, apply auth ...
query_ctx = ctx.query.context
# Some legacy fields can have `nil` here, not exactly sure why.
# @see https://github.com/rmosolgo/graphql-ruby/issues/1990 before removing
inner_obj = after_obj && after_obj.object
ctx.schema.after_lazy(to_ruby_args(after_obj, args, ctx)) do |ruby_args|
if authorized?(inner_obj, ruby_args, query_ctx)
# Then if it passed, resolve the field
if @resolve_proc
# Might be nil, still want to call the func in that case
with_extensions(inner_obj, ruby_args, query_ctx) do |extended_obj, extended_args|
# Pass the GraphQL args here for compatibility:
@resolve_proc.call(extended_obj, args, ctx)
end
else
public_send_field(after_obj, ruby_args, ctx)
end
else
err = GraphQL::UnauthorizedFieldError.new(object: inner_obj, type: obj.class, context: ctx, field: self)
query_ctx.schema.unauthorized_field(err)
end
end
end
end
# This method is called by the interpreter for each field.
# You can extend it in your base field classes.
# @param object [GraphQL::Schema::Object] An instance of some type class, wrapping an application object
# @param args [Hash] A symbol-keyed hash of Ruby keyword arguments. (Empty if no args)
# @param ctx [GraphQL::Query::Context]
def resolve(object, args, ctx)
if @resolve_proc
raise "Can't run resolve proc for #{path} when using GraphQL::Execution::Interpreter"
end
begin
# Unwrap the GraphQL object to get the application object.
application_object = object.object
if self.authorized?(application_object, args, ctx)
# Apply field extensions
with_extensions(object, args, ctx) do |extended_obj, extended_args|
field_receiver = if @resolver_class
resolver_obj = if extended_obj.is_a?(GraphQL::Schema::Object)
extended_obj.object
else
extended_obj
end
@resolver_class.new(object: resolver_obj, context: ctx, field: self)
else
extended_obj
end
if field_receiver.respond_to?(@resolver_method)
# Call the method with kwargs, if there are any
if extended_args.any?
field_receiver.public_send(@resolver_method, **extended_args)
else
field_receiver.public_send(@resolver_method)
end
else
resolve_field_method(field_receiver, extended_args, ctx)
end
end
else
err = GraphQL::UnauthorizedFieldError.new(object: application_object, type: object.class, context: ctx, field: self)
ctx.schema.unauthorized_field(err)
end
rescue GraphQL::UnauthorizedFieldError => err
err.field ||= self
ctx.schema.unauthorized_field(err)
rescue GraphQL::UnauthorizedError => err
ctx.schema.unauthorized_object(err)
end
rescue GraphQL::ExecutionError => err
err
end
# Find a way to resolve this field, checking:
#
# - Hash keys, if the wrapped object is a hash;
# - A method on the wrapped object;
# - Or, raise not implemented.
#
# This can be overridden by defining a method on the object type.
# @param obj [GraphQL::Schema::Object]
# @param ruby_kwargs [Hash<Symbol => Object>]
# @param ctx [GraphQL::Query::Context]
def resolve_field_method(obj, ruby_kwargs, ctx)
if obj.object.is_a?(Hash)
inner_object = obj.object
if inner_object.key?(@method_sym)
inner_object[@method_sym]
else
inner_object[@method_str]
end
elsif obj.object.respond_to?(@method_sym)
if ruby_kwargs.any?
obj.object.public_send(@method_sym, **ruby_kwargs)
else
obj.object.public_send(@method_sym)
end
else
raise <<-ERR
Failed to implement #{@owner.graphql_name}.#{@name}, tried:
- `#{obj.class}##{@resolver_method}`, which did not exist
- `#{obj.object.class}##{@method_sym}`, which did not exist
- Looking up hash key `#{@method_sym.inspect}` or `#{@method_str.inspect}` on `#{obj.object}`, but it wasn't a Hash
To implement this field, define one of the methods above (and check for typos)
ERR
end
end
# @param ctx [GraphQL::Query::Context::FieldResolutionContext]
def fetch_extra(extra_name, ctx)
if extra_name != :path && extra_name != :ast_node && respond_to?(extra_name)
self.public_send(extra_name)
elsif ctx.respond_to?(extra_name)
ctx.public_send(extra_name)
else
raise GraphQL::RequiredImplementationMissingError, "Unknown field extra for #{self.path}: #{extra_name.inspect}"
end
end
private
NO_ARGS = {}.freeze
# Convert a GraphQL arguments instance into a Ruby-style hash.
#
# @param obj [GraphQL::Schema::Object] The object where this field is being resolved
# @param graphql_args [GraphQL::Query::Arguments]
# @param field_ctx [GraphQL::Query::Context::FieldResolutionContext]
# @return [Hash<Symbol => Any>]
def to_ruby_args(obj, graphql_args, field_ctx)
if graphql_args.any? || @extras.any?
# Splat the GraphQL::Arguments to Ruby keyword arguments
ruby_kwargs = graphql_args.to_kwargs
maybe_lazies = []
# Apply any `prepare` methods. Not great code organization, can this go somewhere better?
arguments.each do |name, arg_defn|
ruby_kwargs_key = arg_defn.keyword
if ruby_kwargs.key?(ruby_kwargs_key)
loads = arg_defn.loads
value = ruby_kwargs[ruby_kwargs_key]
loaded_value = if loads && !arg_defn.from_resolver?
if arg_defn.type.list?
loaded_values = value.map { |val| load_application_object(arg_defn, loads, val, field_ctx.query.context) }
maybe_lazies.concat(loaded_values)
else
load_application_object(arg_defn, loads, value, field_ctx.query.context)
end
else
value
end
maybe_lazies << field_ctx.schema.after_lazy(loaded_value) do |loaded_value|
prepared_value = if arg_defn.prepare
arg_defn.prepare_value(obj, loaded_value)
else
loaded_value
end
ruby_kwargs[ruby_kwargs_key] = prepared_value
end
end
end
@extras.each do |extra_arg|
ruby_kwargs[extra_arg] = fetch_extra(extra_arg, field_ctx)
end
field_ctx.schema.after_any_lazies(maybe_lazies) do
ruby_kwargs
end
else
NO_ARGS
end
end
def public_send_field(obj, ruby_kwargs, field_ctx)
query_ctx = field_ctx.query.context
with_extensions(obj, ruby_kwargs, query_ctx) do |extended_obj, extended_args|
if @resolver_class
if extended_obj.is_a?(GraphQL::Schema::Object)
extended_obj = extended_obj.object
end
extended_obj = @resolver_class.new(object: extended_obj, context: query_ctx, field: self)
end
if extended_obj.respond_to?(@resolver_method)
if extended_args.any?
extended_obj.public_send(@resolver_method, **extended_args)
else
extended_obj.public_send(@resolver_method)
end
else
resolve_field_method(extended_obj, extended_args, query_ctx)
end
end
end
# Wrap execution with hooks.
# Written iteratively to avoid big stack traces.
# @return [Object] Whatever the
def with_extensions(obj, args, ctx)
if @extensions.empty?
yield(obj, args)
else
# Save these so that the originals can be re-given to `after_resolve` handlers.
original_args = args
original_obj = obj
memos = []
value = run_extensions_before_resolve(memos, obj, args, ctx) do |extended_obj, extended_args|
yield(extended_obj, extended_args)
end
ctx.schema.after_lazy(value) do |resolved_value|
@extensions.each_with_index do |ext, idx|
memo = memos[idx]
# TODO after_lazy?
resolved_value = ext.after_resolve(object: original_obj, arguments: original_args, context: ctx, value: resolved_value, memo: memo)
end
resolved_value
end
end
end
def run_extensions_before_resolve(memos, obj, args, ctx, idx: 0)
extension = @extensions[idx]
if extension
extension.resolve(object: obj, arguments: args, context: ctx) do |extended_obj, extended_args, memo|
memos << memo
run_extensions_before_resolve(memos, extended_obj, extended_args, ctx, idx: idx + 1) { |o, a| yield(o, a) }
end
else
yield(obj, args)
end
end
end
end
end
update docs
# frozen_string_literal: true
# test_via: ../object.rb
require "graphql/schema/field/connection_extension"
require "graphql/schema/field/scope_extension"
module GraphQL
class Schema
class Field
if !String.method_defined?(:-@)
using GraphQL::StringDedupBackport
end
include GraphQL::Schema::Member::CachedGraphQLDefinition
include GraphQL::Schema::Member::AcceptsDefinition
include GraphQL::Schema::Member::HasArguments
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasPath
extend GraphQL::Schema::FindInheritedValue
include GraphQL::Schema::FindInheritedValue::EmptyObjects
# @return [String] the GraphQL name for this field, camelized unless `camelize: false` is provided
attr_reader :name
alias :graphql_name :name
attr_writer :description
# @return [String, nil] If present, the field is marked as deprecated with this documentation
attr_accessor :deprecation_reason
# @return [Symbol] Method or hash key on the underlying object to look up
attr_reader :method_sym
# @return [String] Method or hash key on the underlying object to look up
attr_reader :method_str
# @return [Symbol] The method on the type to look up
attr_reader :resolver_method
# @return [Class] The type that this field belongs to
attr_accessor :owner
# @return [Symbol] the original name of the field, passed in by the user
attr_reader :original_name
# @return [Class, nil] The {Schema::Resolver} this field was derived from, if there is one
def resolver
@resolver_class
end
alias :mutation :resolver
# @return [Boolean] Apply tracing to this field? (Default: skip scalars, this is the override value)
attr_reader :trace
# @return [String, nil]
attr_accessor :subscription_scope
# Create a field instance from a list of arguments, keyword arguments, and a block.
#
# This method implements prioritization between the `resolver` or `mutation` defaults
# and the local overrides via other keywords.
#
# It also normalizes positional arguments into keywords for {Schema::Field#initialize}.
# @param resolver [Class] A {GraphQL::Schema::Resolver} class to use for field configuration
# @param mutation [Class] A {GraphQL::Schema::Mutation} class to use for field configuration
# @param subscription [Class] A {GraphQL::Schema::Subscription} class to use for field configuration
# @return [GraphQL::Schema:Field] an instance of `self
# @see {.initialize} for other options
def self.from_options(name = nil, type = nil, desc = nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
if kwargs[:field]
if kwargs[:field] == GraphQL::Relay::Node.field
warn("Legacy-style `GraphQL::Relay::Node.field` is being added to a class-based type. See `GraphQL::Types::Relay::NodeField` for a replacement.")
return GraphQL::Types::Relay::NodeField
elsif kwargs[:field] == GraphQL::Relay::Node.plural_field
warn("Legacy-style `GraphQL::Relay::Node.plural_field` is being added to a class-based type. See `GraphQL::Types::Relay::NodesField` for a replacement.")
return GraphQL::Types::Relay::NodesField
end
end
if (parent_config = resolver || mutation || subscription)
# Get the parent config, merge in local overrides
kwargs = parent_config.field_options.merge(kwargs)
# Add a reference to that parent class
kwargs[:resolver_class] = parent_config
end
if name
kwargs[:name] = name
end
if !type.nil?
if type.is_a?(GraphQL::Field)
raise ArgumentError, "A GraphQL::Field was passed as the second argument, use the `field:` keyword for this instead."
end
if desc
if kwargs[:description]
raise ArgumentError, "Provide description as a positional argument or `description:` keyword, but not both (#{desc.inspect}, #{kwargs[:description].inspect})"
end
kwargs[:description] = desc
kwargs[:type] = type
elsif (kwargs[:field] || kwargs[:function] || resolver || mutation) && type.is_a?(String)
# The return type should be copied from `field` or `function`, and the second positional argument is the description
kwargs[:description] = type
else
kwargs[:type] = type
end
end
new(**kwargs, &block)
end
# Can be set with `connection: true|false` or inferred from a type name ending in `*Connection`
# @return [Boolean] if true, this field will be wrapped with Relay connection behavior
def connection?
if @connection.nil?
# Provide default based on type name
return_type_name = if (contains_type = @field || @function)
Member::BuildType.to_type_name(contains_type.type)
elsif @return_type_expr
Member::BuildType.to_type_name(@return_type_expr)
else
# As a last ditch, try to force loading the return type:
type.unwrap.name
end
@connection = return_type_name.end_with?("Connection")
else
@connection
end
end
# @return [Boolean] if true, the return type's `.scope_items` method will be applied to this field's return value
def scoped?
if !@scope.nil?
# The default was overridden
@scope
else
@return_type_expr && (@return_type_expr.is_a?(Array) || (@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) || connection?)
end
end
# This extension is applied to fields when {#connection?} is true.
#
# You can override it in your base field definition.
# @return [Class] A {FieldExtension} subclass for implementing pagination behavior.
# @example Configuring a custom extension
# class Types::BaseField < GraphQL::Schema::Field
# connection_extension(MyCustomExtension)
# end
def self.connection_extension(new_extension_class = nil)
if new_extension_class
@connection_extension = new_extension_class
else
@connection_extension ||= find_inherited_value(:connection_extension, ConnectionExtension)
end
end
# @return Boolean
attr_reader :relay_node_field
# @return [Boolean] Should we warn if this field's name conflicts with a built-in method?
def method_conflict_warning?
@method_conflict_warning
end
# @param name [Symbol] The underscore-cased version of this field name (will be camelized for the GraphQL API)
# @param type [Class, GraphQL::BaseType, Array] The return type of this field
# @param owner [Class] The type that this field belongs to
# @param null [Boolean] `true` if this field may return `null`, `false` if it is never `null`
# @param description [String] Field description
# @param deprecation_reason [String] If present, the field is marked "deprecated" with this message
# @param method [Symbol] The method to call on the underlying object to resolve this field (defaults to `name`)
# @param hash_key [String, Symbol] The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults to `name` or `name.to_s`)
# @param resolver_method [Symbol] The method on the type to call to resolve this field (defaults to `name`)
# @param connection [Boolean] `true` if this field should get automagic connection behavior; default is to infer by `*Connection` in the return type name
# @param connection_extension [Class] The extension to add, to implement connections. If `nil`, no extension is added.
# @param max_page_size [Integer, nil] For connections, the maximum number of items to return from this field, or `nil` to allow unlimited results.
# @param introspection [Boolean] If true, this field will be marked as `#introspection?` and the name may begin with `__`
# @param resolve [<#call(obj, args, ctx)>] **deprecated** for compatibility with <1.8.0
# @param field [GraphQL::Field, GraphQL::Schema::Field] **deprecated** for compatibility with <1.8.0
# @param function [GraphQL::Function] **deprecated** for compatibility with <1.8.0
# @param resolver_class [Class] (Private) A {Schema::Resolver} which this field was derived from. Use `resolver:` to create a field with a resolver.
# @param arguments [{String=>GraphQL::Schema::Argument, Hash}] Arguments for this field (may be added in the block, also)
# @param camelize [Boolean] If true, the field name will be camelized when building the schema
# @param complexity [Numeric] When provided, set the complexity for this field
# @param scope [Boolean] If true, the return type's `.scope_items` method will be called on the return value
# @param subscription_scope [Symbol, String] A key in `context` which will be used to scope subscription payloads
# @param extensions [Array<Class, Hash<Class => Object>>] Named extensions to apply to this field (see also {#extension})
# @param trace [Boolean] If true, a {GraphQL::Tracing} tracer will measure this scalar field
# @param ast_node [Language::Nodes::FieldDefinition, nil] If this schema was parsed from definition, this AST node defined the field
# @param method_conflict_warning [Boolean] If false, skip the warning if this field's method conflicts with a built-in method
def initialize(type: nil, name: nil, owner: nil, null: nil, field: nil, function: nil, description: nil, deprecation_reason: nil, method: nil, hash_key: nil, resolver_method: nil, resolve: nil, connection: nil, max_page_size: :not_given, scope: nil, introspection: false, camelize: true, trace: nil, complexity: 1, ast_node: nil, extras: [], extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, arguments: EMPTY_HASH, &definition_block)
if name.nil?
raise ArgumentError, "missing first `name` argument or keyword `name:`"
end
if !(field || function || resolver_class)
if type.nil?
raise ArgumentError, "missing second `type` argument or keyword `type:`"
end
if null.nil?
raise ArgumentError, "missing keyword argument null:"
end
end
if (field || function || resolve) && extras.any?
raise ArgumentError, "keyword `extras:` may only be used with method-based resolve and class-based field such as mutation class, please remove `field:`, `function:` or `resolve:`"
end
@original_name = name
name_s = -name.to_s
@underscored_name = -Member::BuildType.underscore(name_s)
@name = -(camelize ? Member::BuildType.camelize(name_s) : name_s)
@description = description
if field.is_a?(GraphQL::Schema::Field)
raise ArgumentError, "Instead of passing a field as `field:`, use `add_field(field)` to add an already-defined field."
else
@field = field
end
@function = function
@resolve = resolve
@deprecation_reason = deprecation_reason
if method && hash_key
raise ArgumentError, "Provide `method:` _or_ `hash_key:`, not both. (called with: `method: #{method.inspect}, hash_key: #{hash_key.inspect}`)"
end
if resolver_method
if method
raise ArgumentError, "Provide `method:` _or_ `resolver_method:`, not both. (called with: `method: #{method.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
if hash_key
raise ArgumentError, "Provide `hash_key:` _or_ `resolver_method:`, not both. (called with: `hash_key: #{hash_key.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
end
# TODO: I think non-string/symbol hash keys are wrongly normalized (eg `1` will not work)
method_name = method || hash_key || @underscored_name
resolver_method ||= @underscored_name.to_sym
@method_str = method_name.to_s
@method_sym = method_name.to_sym
@resolver_method = resolver_method
@complexity = complexity
@return_type_expr = type
@return_type_null = null
@connection = connection
@has_max_page_size = max_page_size != :not_given
@max_page_size = max_page_size
@introspection = introspection
@extras = extras
@resolver_class = resolver_class
@scope = scope
@trace = trace
@relay_node_field = relay_node_field
@relay_nodes_field = relay_nodes_field
@ast_node = ast_node
@method_conflict_warning = method_conflict_warning
arguments.each do |name, arg|
if arg.is_a?(Hash)
argument(name: name, **arg)
else
own_arguments[name] = arg
end
end
@owner = owner
@subscription_scope = subscription_scope
# Do this last so we have as much context as possible when initializing them:
@extensions = []
if extensions.any?
self.extensions(extensions)
end
# This should run before connection extension,
# but should it run after the definition block?
if scoped?
self.extension(ScopeExtension)
end
# The problem with putting this after the definition_block
# is that it would override arguments
if connection? && connection_extension
self.extension(connection_extension)
end
if definition_block
if definition_block.arity == 1
yield self
else
instance_eval(&definition_block)
end
end
end
# @param text [String]
# @return [String]
def description(text = nil)
if text
@description = text
else
@description
end
end
# Read extension instances from this field,
# or add new classes/options to be initialized on this field.
# Extensions are executed in the order they are added.
#
# @example adding an extension
# extensions([MyExtensionClass])
#
# @example adding multiple extensions
# extensions([MyExtensionClass, AnotherExtensionClass])
#
# @example adding an extension with options
# extensions([MyExtensionClass, { AnotherExtensionClass => { filter: true } }])
#
# @param extensions [Array<Class, Hash<Class => Object>>] Add extensions to this field. For hash elements, only the first key/value is used.
# @return [Array<GraphQL::Schema::FieldExtension>] extensions to apply to this field
def extensions(new_extensions = nil)
if new_extensions.nil?
# Read the value
@extensions
else
new_extensions.each do |extension|
if extension.is_a?(Hash)
extension = extension.to_a[0]
extension_class, options = *extension
@extensions << extension_class.new(field: self, options: options)
else
extension_class = extension
@extensions << extension_class.new(field: self, options: nil)
end
end
end
end
# Add `extension` to this field, initialized with `options` if provided.
#
# @example adding an extension
# extension(MyExtensionClass)
#
# @example adding an extension with options
# extension(MyExtensionClass, filter: true)
#
# @param extension [Class] subclass of {Schema::Fieldextension}
# @param options [Object] if provided, given as `options:` when initializing `extension`.
def extension(extension, options = nil)
extensions([{extension => options}])
end
# Read extras (as symbols) from this field,
# or add new extras to be opted into by this field's resolver.
#
# @param new_extras [Array<Symbol>] Add extras to this field
# @return [Array<Symbol>]
def extras(new_extras = nil)
if new_extras.nil?
# Read the value
@extras
else
# Append to the set of extras on this field
@extras.concat(new_extras)
end
end
def complexity(new_complexity = nil)
case new_complexity
when Proc
if new_complexity.parameters.size != 3
fail(
"A complexity proc should always accept 3 parameters: ctx, args, child_complexity. "\
"E.g.: complexity ->(ctx, args, child_complexity) { child_complexity * args[:limit] }"
)
else
@complexity = new_complexity
end
when Numeric
@complexity = new_complexity
when nil
@complexity
else
raise("Invalid complexity: #{new_complexity.inspect} on #{@name}")
end
end
# @return [Boolean] True if this field's {#max_page_size} should override the schema default.
def has_max_page_size?
@has_max_page_size
end
# @return [Integer, nil] Applied to connections if {#has_max_page_size?}
attr_reader :max_page_size
# @return [GraphQL::Field]
def to_graphql
field_defn = if @field
@field.dup
elsif @function
GraphQL::Function.build_field(@function)
else
GraphQL::Field.new
end
field_defn.name = @name
if @return_type_expr
field_defn.type = -> { type }
end
if @description
field_defn.description = @description
end
if @deprecation_reason
field_defn.deprecation_reason = @deprecation_reason
end
if @resolver_class
if @resolver_class < GraphQL::Schema::Mutation
field_defn.mutation = @resolver_class
end
field_defn.metadata[:resolver] = @resolver_class
end
if !@trace.nil?
field_defn.trace = @trace
end
if @relay_node_field
field_defn.relay_node_field = @relay_node_field
end
if @relay_nodes_field
field_defn.relay_nodes_field = @relay_nodes_field
end
field_defn.resolve = self.method(:resolve_field)
field_defn.connection = connection?
field_defn.connection_max_page_size = max_page_size
field_defn.introspection = @introspection
field_defn.complexity = @complexity
field_defn.subscription_scope = @subscription_scope
field_defn.ast_node = ast_node
arguments.each do |name, defn|
arg_graphql = defn.to_graphql
field_defn.arguments[arg_graphql.name] = arg_graphql
end
# Support a passed-in proc, one way or another
@resolve_proc = if @resolve
@resolve
elsif @function
@function
elsif @field
@field.resolve_proc
end
# Ok, `self` isn't a class, but this is for consistency with the classes
field_defn.metadata[:type_class] = self
field_defn.arguments_class = GraphQL::Query::Arguments.construct_arguments_class(field_defn)
field_defn
end
attr_writer :type
def type
@type ||= if @function
Member::BuildType.parse_type(@function.type, null: false)
elsif @field
Member::BuildType.parse_type(@field.type, null: false)
else
Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
end
rescue GraphQL::Schema::InvalidDocumentError => err
# Let this propagate up
raise err
rescue StandardError => err
raise ArgumentError, "Failed to build return type for #{@owner.graphql_name}.#{name} from #{@return_type_expr.inspect}: (#{err.class}) #{err.message}", err.backtrace
end
def visible?(context)
if @resolver_class
@resolver_class.visible?(context)
else
true
end
end
def accessible?(context)
if @resolver_class
@resolver_class.accessible?(context)
else
true
end
end
def authorized?(object, args, context)
if @resolver_class
# The resolver will check itself during `resolve()`
@resolver_class.authorized?(object, context)
else
# Faster than `.any?`
arguments.each_value do |arg|
if args.key?(arg.keyword) && !arg.authorized?(object, args[arg.keyword], context)
return false
end
end
true
end
end
# Implement {GraphQL::Field}'s resolve API.
#
# Eventually, we might hook up field instances to execution in another way. TBD.
# @see #resolve for how the interpreter hooks up to it
def resolve_field(obj, args, ctx)
ctx.schema.after_lazy(obj) do |after_obj|
# First, apply auth ...
query_ctx = ctx.query.context
# Some legacy fields can have `nil` here, not exactly sure why.
# @see https://github.com/rmosolgo/graphql-ruby/issues/1990 before removing
inner_obj = after_obj && after_obj.object
ctx.schema.after_lazy(to_ruby_args(after_obj, args, ctx)) do |ruby_args|
if authorized?(inner_obj, ruby_args, query_ctx)
# Then if it passed, resolve the field
if @resolve_proc
# Might be nil, still want to call the func in that case
with_extensions(inner_obj, ruby_args, query_ctx) do |extended_obj, extended_args|
# Pass the GraphQL args here for compatibility:
@resolve_proc.call(extended_obj, args, ctx)
end
else
public_send_field(after_obj, ruby_args, ctx)
end
else
err = GraphQL::UnauthorizedFieldError.new(object: inner_obj, type: obj.class, context: ctx, field: self)
query_ctx.schema.unauthorized_field(err)
end
end
end
end
# This method is called by the interpreter for each field.
# You can extend it in your base field classes.
# @param object [GraphQL::Schema::Object] An instance of some type class, wrapping an application object
# @param args [Hash] A symbol-keyed hash of Ruby keyword arguments. (Empty if no args)
# @param ctx [GraphQL::Query::Context]
def resolve(object, args, ctx)
if @resolve_proc
raise "Can't run resolve proc for #{path} when using GraphQL::Execution::Interpreter"
end
begin
# Unwrap the GraphQL object to get the application object.
application_object = object.object
if self.authorized?(application_object, args, ctx)
# Apply field extensions
with_extensions(object, args, ctx) do |extended_obj, extended_args|
field_receiver = if @resolver_class
resolver_obj = if extended_obj.is_a?(GraphQL::Schema::Object)
extended_obj.object
else
extended_obj
end
@resolver_class.new(object: resolver_obj, context: ctx, field: self)
else
extended_obj
end
if field_receiver.respond_to?(@resolver_method)
# Call the method with kwargs, if there are any
if extended_args.any?
field_receiver.public_send(@resolver_method, **extended_args)
else
field_receiver.public_send(@resolver_method)
end
else
resolve_field_method(field_receiver, extended_args, ctx)
end
end
else
err = GraphQL::UnauthorizedFieldError.new(object: application_object, type: object.class, context: ctx, field: self)
ctx.schema.unauthorized_field(err)
end
rescue GraphQL::UnauthorizedFieldError => err
err.field ||= self
ctx.schema.unauthorized_field(err)
rescue GraphQL::UnauthorizedError => err
ctx.schema.unauthorized_object(err)
end
rescue GraphQL::ExecutionError => err
err
end
# Find a way to resolve this field, checking:
#
# - Hash keys, if the wrapped object is a hash;
# - A method on the wrapped object;
# - Or, raise not implemented.
#
# This can be overridden by defining a method on the object type.
# @param obj [GraphQL::Schema::Object]
# @param ruby_kwargs [Hash<Symbol => Object>]
# @param ctx [GraphQL::Query::Context]
def resolve_field_method(obj, ruby_kwargs, ctx)
if obj.object.is_a?(Hash)
inner_object = obj.object
if inner_object.key?(@method_sym)
inner_object[@method_sym]
else
inner_object[@method_str]
end
elsif obj.object.respond_to?(@method_sym)
if ruby_kwargs.any?
obj.object.public_send(@method_sym, **ruby_kwargs)
else
obj.object.public_send(@method_sym)
end
else
raise <<-ERR
Failed to implement #{@owner.graphql_name}.#{@name}, tried:
- `#{obj.class}##{@resolver_method}`, which did not exist
- `#{obj.object.class}##{@method_sym}`, which did not exist
- Looking up hash key `#{@method_sym.inspect}` or `#{@method_str.inspect}` on `#{obj.object}`, but it wasn't a Hash
To implement this field, define one of the methods above (and check for typos)
ERR
end
end
# @param ctx [GraphQL::Query::Context::FieldResolutionContext]
def fetch_extra(extra_name, ctx)
if extra_name != :path && extra_name != :ast_node && respond_to?(extra_name)
self.public_send(extra_name)
elsif ctx.respond_to?(extra_name)
ctx.public_send(extra_name)
else
raise GraphQL::RequiredImplementationMissingError, "Unknown field extra for #{self.path}: #{extra_name.inspect}"
end
end
private
NO_ARGS = {}.freeze
# Convert a GraphQL arguments instance into a Ruby-style hash.
#
# @param obj [GraphQL::Schema::Object] The object where this field is being resolved
# @param graphql_args [GraphQL::Query::Arguments]
# @param field_ctx [GraphQL::Query::Context::FieldResolutionContext]
# @return [Hash<Symbol => Any>]
def to_ruby_args(obj, graphql_args, field_ctx)
if graphql_args.any? || @extras.any?
# Splat the GraphQL::Arguments to Ruby keyword arguments
ruby_kwargs = graphql_args.to_kwargs
maybe_lazies = []
# Apply any `prepare` methods. Not great code organization, can this go somewhere better?
arguments.each do |name, arg_defn|
ruby_kwargs_key = arg_defn.keyword
if ruby_kwargs.key?(ruby_kwargs_key)
loads = arg_defn.loads
value = ruby_kwargs[ruby_kwargs_key]
loaded_value = if loads && !arg_defn.from_resolver?
if arg_defn.type.list?
loaded_values = value.map { |val| load_application_object(arg_defn, loads, val, field_ctx.query.context) }
maybe_lazies.concat(loaded_values)
else
load_application_object(arg_defn, loads, value, field_ctx.query.context)
end
else
value
end
maybe_lazies << field_ctx.schema.after_lazy(loaded_value) do |loaded_value|
prepared_value = if arg_defn.prepare
arg_defn.prepare_value(obj, loaded_value)
else
loaded_value
end
ruby_kwargs[ruby_kwargs_key] = prepared_value
end
end
end
@extras.each do |extra_arg|
ruby_kwargs[extra_arg] = fetch_extra(extra_arg, field_ctx)
end
field_ctx.schema.after_any_lazies(maybe_lazies) do
ruby_kwargs
end
else
NO_ARGS
end
end
def public_send_field(obj, ruby_kwargs, field_ctx)
query_ctx = field_ctx.query.context
with_extensions(obj, ruby_kwargs, query_ctx) do |extended_obj, extended_args|
if @resolver_class
if extended_obj.is_a?(GraphQL::Schema::Object)
extended_obj = extended_obj.object
end
extended_obj = @resolver_class.new(object: extended_obj, context: query_ctx, field: self)
end
if extended_obj.respond_to?(@resolver_method)
if extended_args.any?
extended_obj.public_send(@resolver_method, **extended_args)
else
extended_obj.public_send(@resolver_method)
end
else
resolve_field_method(extended_obj, extended_args, query_ctx)
end
end
end
# Wrap execution with hooks.
# Written iteratively to avoid big stack traces.
# @return [Object] Whatever the
def with_extensions(obj, args, ctx)
if @extensions.empty?
yield(obj, args)
else
# Save these so that the originals can be re-given to `after_resolve` handlers.
original_args = args
original_obj = obj
memos = []
value = run_extensions_before_resolve(memos, obj, args, ctx) do |extended_obj, extended_args|
yield(extended_obj, extended_args)
end
ctx.schema.after_lazy(value) do |resolved_value|
@extensions.each_with_index do |ext, idx|
memo = memos[idx]
# TODO after_lazy?
resolved_value = ext.after_resolve(object: original_obj, arguments: original_args, context: ctx, value: resolved_value, memo: memo)
end
resolved_value
end
end
end
def run_extensions_before_resolve(memos, obj, args, ctx, idx: 0)
extension = @extensions[idx]
if extension
extension.resolve(object: obj, arguments: args, context: ctx) do |extended_obj, extended_args, memo|
memos << memo
run_extensions_before_resolve(memos, extended_obj, extended_args, ctx, idx: idx + 1) { |o, a| yield(o, a) }
end
else
yield(obj, args)
end
end
end
end
end
|
require 'harvest_slack_report/version'
require 'harvested'
require 'slack-ruby-client'
require 'active_support/all'
# Posts summary harvest data to a slack channel
module HarvestSlackReport
def self.fetch_harvest_data(from_date)
domain = ENV.fetch 'HARVEST_DOMAIN'
username = ENV.fetch 'HARVEST_USERNAME'
password = ENV.fetch 'HARVEST_PASSWORD'
puts "Collecting Harvest data for #{domain}..."
harvest = Harvest.hardy_client(subdomain: domain,
username: username,
password: password
)
ignore_users = if ENV['IGNORE_USERS'].present?
ENV['IGNORE_USERS'].split(',').map{ |user_id| user_id.to_i }
else
[]
end
people = harvest.users.all.select { |u| u.is_active? && !ignore_users.include?(u.id) }
# puts people.map{ |u| u.email }
projects = harvest.projects.all
# puts projects
puts 'Aggregating data...'
report = []
n_people = people.count
people.each_with_index do |person, i|
# TODO Make this customisable
# Timesheet entries for yesterday
entries = harvest.reports.time_by_user(person.id, from_date, Time.now)
name = "#{person.first_name} #{person.last_name}"
if entries.any?
total_hours = entries.map { |x| x.hours }.sum.round(2)
hours_by_project = entries.group_by { |x| x.project_id }.map do |project_id, es|
proj = projects.find { |pr| pr.id == project_id }
title = "#{proj.code.present? ? "[#{proj.code}] " : ''}#{proj.name}"
{ title: title, value: es.map { |h| h.hours }.sum.round(2), short: true }
end
color_code = case total_hours
when 0..2
"#D0021B"
when 2..4
"#F59423"
when 4..5
"#F8C61C"
else
"#72D321"
end
report << { fallback: "#{name} logged #{total_hours} hours",
text: "#{name} logged #{total_hours} hours",
fields: hours_by_project,
color: color_code
}
else
report << { fallback: "#{name} logged no time", text: "#{name} logged no time", color: "#4A4A4A" }
end
puts "#{i+1}/#{n_people}"
end
report
end
def self.run
from_date = Time.now - 1.day
report = fetch_harvest_data(from_date)
if ENV['SLACK_API_TOKEN'].present?
puts 'Posting to Slack'
Slack.configure do |config|
config.token = ENV['SLACK_API_TOKEN']
end
client = Slack::Web::Client.new
client.auth_test
client.chat_postMessage(channel: '#2-standup',
text: "Time Report from #{from_date.to_formatted_s(:rfc822)} to now:",
attachments: report,
as_user: true
)
else
puts report.inspect
end
end
end
check if entries is nil
require 'harvest_slack_report/version'
require 'harvested'
require 'slack-ruby-client'
require 'active_support/all'
# Posts summary harvest data to a slack channel
module HarvestSlackReport
def self.fetch_harvest_data(from_date)
domain = ENV.fetch 'HARVEST_DOMAIN'
username = ENV.fetch 'HARVEST_USERNAME'
password = ENV.fetch 'HARVEST_PASSWORD'
puts "Collecting Harvest data for #{domain}..."
harvest = Harvest.hardy_client(subdomain: domain,
username: username,
password: password
)
ignore_users = if ENV['IGNORE_USERS'].present?
ENV['IGNORE_USERS'].split(',').map{ |user_id| user_id.to_i }
else
[]
end
people = harvest.users.all.select { |u| u.is_active? && !ignore_users.include?(u.id) }
# puts people.map{ |u| u.email }
projects = harvest.projects.all
# puts projects
puts 'Aggregating data...'
report = []
n_people = people.count
people.each_with_index do |person, i|
# TODO Make this customisable
# Timesheet entries for yesterday
entries = harvest.reports.time_by_user(person.id, from_date, Time.now)
name = "#{person.first_name} #{person.last_name}"
if entries && entries.any?
total_hours = entries.map { |x| x.hours }.sum.round(2)
hours_by_project = entries.group_by { |x| x.project_id }.map do |project_id, es|
proj = projects.find { |pr| pr.id == project_id }
title = "#{proj.code.present? ? "[#{proj.code}] " : ''}#{proj.name}"
{ title: title, value: es.map { |h| h.hours }.sum.round(2), short: true }
end
color_code = case total_hours
when 0..2
"#D0021B"
when 2..4
"#F59423"
when 4..5
"#F8C61C"
else
"#72D321"
end
report << { fallback: "#{name} logged #{total_hours} hours",
text: "#{name} logged #{total_hours} hours",
fields: hours_by_project,
color: color_code
}
else
report << { fallback: "#{name} logged no time", text: "#{name} logged no time", color: "#4A4A4A" }
end
puts "#{i+1}/#{n_people}"
end
report
end
def self.run
from_date = Time.now - 1.day
report = fetch_harvest_data(from_date)
if ENV['SLACK_API_TOKEN'].present?
puts 'Posting to Slack'
Slack.configure do |config|
config.token = ENV['SLACK_API_TOKEN']
end
client = Slack::Web::Client.new
client.auth_test
client.chat_postMessage(channel: '#2-standup',
text: "Time Report from #{from_date.to_formatted_s(:rfc822)} to now:",
attachments: report,
as_user: true
)
else
puts report.inspect
end
end
end
|
unless defined?(BasicObject)
require 'blankslate'
BasicObject = BlankSlate
end
# = BasicStruct
#
# BasicObject is very similar to Ruby's own OpenStruct, but it offers some
# advantages. With OpenStruct, slots with the same name as predefined
# Object methods cannot be used. With BasicObject, almost any slot can be
# defined. BasicObject is a subclass of BasicObject to ensure all method
# slots, except those that are absolutely essential, are open for use.
#
#--
# If you wish to pass an BasicObject to a routine that normal takes a Hash,
# but are uncertain it can handle the distictions properly you can convert
# easily to a Hash using #as_hash! and the result will automatically be
# converted back to an BasicObject on return.
#
# o = BasicObject.new(:a=>1,:b=>2)
# o.as_hash!{ |h| h.update(:a=>6) }
# o #=> #<BasicObject {:a=>6,:b=>2}>
#++
#
# Unlike a Hash, all BasicObject's keys are symbols and all keys are converted
# to such using #to_sym on the fly.
class BasicStruct < BasicObject
#PUBLIC_METHODS = /(^__|^instance_|^object_|^\W|^as$|^send$|^class$|\?$)/
#protected(*public_instance_methods.select{ |m| m !~ PUBLIC_METHODS })
def self.[](hash=nil)
new(hash)
end
# Inititalizer for BasicObject is slightly different than that of Hash.
# It does not take a default parameter, but an initial priming Hash,
# like OpenStruct. The initializer can still take a default block
# however. To set the default value use <code>#default!(value)</code>.
#
# BasicObject.new(:a=>1).default!(0)
#
def initialize(hash=nil, &yld)
@table = ::Hash.new(&yld)
if hash
hash.each{ |k,v| store(k,v) }
end
end
#
def initialize_copy(orig)
orig.each{ |k,v| store(k,v) }
end
# Object inspection.
# TODO: Need to get __class__ and __id__ in hex form.
def inspect
#@table.inspect
hexid = __id__
klass = "BasicObject" # __class__
"#<#{klass}:#{hexid} #{@table.inspect}>"
end
# Convert to an associative array.
def to_a
@table.to_a
end
#
def to_h
@table.dup
end
#
def to_hash
@table.dup
end
#
def to_basicstruct
self
end
# Convert to an assignment procedure.
def to_proc(response=false)
hash = @table
if response
::Proc.new do |o|
hash.each do |k,v|
o.__send__("#{k}=", v) rescue nil
end
end
else
::Proc.new do |o|
hash.each{ |k,v| o.__send__("#{k}=", v) }
end
end
end
# NOT SURE ABOUT THIS
def as_hash
@table
end
# Is a given +key+ defined?
def key?(key)
@table.key?(key.to_sym)
end
#
def is_a?(klass)
return true if klass == ::Hash # TODO: Is this wise? How to fake a subclass?
return true if klass == ::BasicObject
false
end
# Iterate over each key-value pair.
def each(&yld)
@table.each(&yld)
end
# Set the default value.
def default!(default)
@table.default = default
end
# Check equality.
def ==( other )
case other
when ::BasicStruct
@table == other.as_hash
when ::Hash
@table == other
else
if other.respond_to?(:to_hash)
@table == other.to_hash
else
false
end
end
end
#
def eql?( other )
case other
when ::BasicStruct
@table.eql?(other.as_hash)
else
false
end
end
#
def <<(x)
case x
when ::Hash
@table.update(x)
when ::Array
x.each_slice(2) do |(k,v)|
@table[k] = v
end
end
end
#
def []=(key, value)
@table[key.to_sym] = value
end
#
def [](key)
@table[key.to_sym]
end
#
def merge!(other)
BasicObject.new(@table.merge!(other))
end
#
def update!(other)
@table.update(other)
self
end
#
def respond_to?(key)
key?(key)
end
# NOTE: These were protected, why?
#
def store(k, v)
@table.store(k.to_sym, v)
end
#
def fetch(k, *d, &b)
@table.fetch(k.to_sym, *d, &b)
end
protected
#def as_hash!
# Functor.new do |op,*a,&b|
# result = @table.__send__(op,*a,&b)
# case result
# when Hash
# BasicObject.new(result)
# else
# result
# end
# end
#end
#def define_slot(key, value=nil)
# @table[key.to_sym] = value
#end
#def protect_slot( key )
# (class << self; self; end).class_eval {
# protected key rescue nil
# }
#end
def method_missing(sym, *args, &blk)
type = sym.to_s[-1,1]
key = sym.to_s.sub(/[=?!]$/,'').to_sym
case type
when '='
store(key, args[0])
when '!'
@table.__send__(key, *args, &blk)
# if key?(key)
# fetch(key)
# else
# store(key, BasicObject.new)
# end
when '?'
fetch(key)
else
fetch(key)
end
end
end
# Core Extensions
class Hash
# Convert a Hash into a BasicStruct.
def to_basicstruct
BasicStruct[self]
end
end
=begin
class NilClass
# Nil converts to an empty BasicObject.
def to_basicstruct
BasicObject.new
end
end
class Proc
# Translates a Proc into an BasicObject. By droping an BasicObject into
# the Proc, the resulting assignments incured as the procedure is
# evaluated produce the BasicObject. This technique is simlar to that
# of MethodProbe.
#
# p = lambda { |x|
# x.word = "Hello"
# }
# o = p.to_basicstruct
# o.word #=> "Hello"
#
# NOTE The Proc must have an arity of one --no more and no less.
def to_basicstruct
raise ArgumentError, 'bad arity for converting Proc to basicstruct' if arity != 1
o = BasicObject.new
self.call( o )
o
end
end
=end
Fix BasicStruct documentation. [doc]
unless defined?(BasicObject)
require 'blankslate'
BasicObject = BlankSlate
end
# = BasicStruct
#
# BasicStruct is very similar to Ruby's own OpenStruct, but it offers some
# advantages. With OpenStruct, slots with the same name as predefined
# Object methods cannot be used. With BasicStruct, almost any slot can be
# defined. BasicStruct is a subclass of BasicObject to ensure all method
# slots, except those that are absolutely essential, are open for use.
#
#--
# If you wish to pass a BasicStruct to a routine that normal takes a Hash,
# but are uncertain it can handle the distictions properly you can convert
# easily to a Hash using #as_hash! and the result will automatically be
# converted back to an BasicStruct on return.
#
# o = BasicStruct.new(:a=>1,:b=>2)
# o.as_hash!{ |h| h.update(:a=>6) }
# o #=> #<BasicObject {:a=>6,:b=>2}>
#++
#
# Unlike a Hash, all BasicStruct's keys are symbols and all keys are converted
# to such using #to_sym on the fly.
class BasicStruct < BasicObject
#PUBLIC_METHODS = /(^__|^instance_|^object_|^\W|^as$|^send$|^class$|\?$)/
#protected(*public_instance_methods.select{ |m| m !~ PUBLIC_METHODS })
def self.[](hash=nil)
new(hash)
end
# Inititalizer for BasicObject is slightly different than that of Hash.
# It does not take a default parameter, but an initial priming Hash,
# like OpenStruct. The initializer can still take a default block
# however. To set the default value use <code>#default!(value)</code>.
#
# BasicObject.new(:a=>1).default!(0)
#
def initialize(hash=nil, &yld)
@table = ::Hash.new(&yld)
if hash
hash.each{ |k,v| store(k,v) }
end
end
#
def initialize_copy(orig)
orig.each{ |k,v| store(k,v) }
end
# Object inspection.
# TODO: Need to get __class__ and __id__ in hex form.
def inspect
#@table.inspect
hexid = __id__
klass = "BasicObject" # __class__
"#<#{klass}:#{hexid} #{@table.inspect}>"
end
# Convert to an associative array.
def to_a
@table.to_a
end
#
def to_h
@table.dup
end
#
def to_hash
@table.dup
end
#
def to_basicstruct
self
end
# Convert to an assignment procedure.
def to_proc(response=false)
hash = @table
if response
::Proc.new do |o|
hash.each do |k,v|
o.__send__("#{k}=", v) rescue nil
end
end
else
::Proc.new do |o|
hash.each{ |k,v| o.__send__("#{k}=", v) }
end
end
end
# NOT SURE ABOUT THIS
def as_hash
@table
end
# Is a given +key+ defined?
def key?(key)
@table.key?(key.to_sym)
end
#
def is_a?(klass)
return true if klass == ::Hash # TODO: Is this wise? How to fake a subclass?
return true if klass == ::BasicObject
false
end
# Iterate over each key-value pair.
def each(&yld)
@table.each(&yld)
end
# Set the default value.
def default!(default)
@table.default = default
end
# Check equality.
def ==( other )
case other
when ::BasicStruct
@table == other.as_hash
when ::Hash
@table == other
else
if other.respond_to?(:to_hash)
@table == other.to_hash
else
false
end
end
end
#
def eql?( other )
case other
when ::BasicStruct
@table.eql?(other.as_hash)
else
false
end
end
#
def <<(x)
case x
when ::Hash
@table.update(x)
when ::Array
x.each_slice(2) do |(k,v)|
@table[k] = v
end
end
end
#
def []=(key, value)
@table[key.to_sym] = value
end
#
def [](key)
@table[key.to_sym]
end
#
def merge!(other)
BasicObject.new(@table.merge!(other))
end
#
def update!(other)
@table.update(other)
self
end
#
def respond_to?(key)
key?(key)
end
# NOTE: These were protected, why?
#
def store(k, v)
@table.store(k.to_sym, v)
end
#
def fetch(k, *d, &b)
@table.fetch(k.to_sym, *d, &b)
end
protected
#def as_hash!
# Functor.new do |op,*a,&b|
# result = @table.__send__(op,*a,&b)
# case result
# when Hash
# BasicObject.new(result)
# else
# result
# end
# end
#end
#def define_slot(key, value=nil)
# @table[key.to_sym] = value
#end
#def protect_slot( key )
# (class << self; self; end).class_eval {
# protected key rescue nil
# }
#end
def method_missing(sym, *args, &blk)
type = sym.to_s[-1,1]
key = sym.to_s.sub(/[=?!]$/,'').to_sym
case type
when '='
store(key, args[0])
when '!'
@table.__send__(key, *args, &blk)
# if key?(key)
# fetch(key)
# else
# store(key, BasicObject.new)
# end
when '?'
fetch(key)
else
fetch(key)
end
end
end
# Core Extensions
class Hash
# Convert a Hash into a BasicStruct.
def to_basicstruct
BasicStruct[self]
end
end
=begin
class NilClass
# Nil converts to an empty BasicObject.
def to_basicstruct
BasicObject.new
end
end
class Proc
# Translates a Proc into an BasicObject. By droping an BasicObject into
# the Proc, the resulting assignments incured as the procedure is
# evaluated produce the BasicObject. This technique is simlar to that
# of MethodProbe.
#
# p = lambda { |x|
# x.word = "Hello"
# }
# o = p.to_basicstruct
# o.word #=> "Hello"
#
# NOTE The Proc must have an arity of one --no more and no less.
def to_basicstruct
raise ArgumentError, 'bad arity for converting Proc to basicstruct' if arity != 1
o = BasicObject.new
self.call( o )
o
end
end
=end
|
#!/usr/bin/env ruby
# coding: utf-8
# rubocop:disable LineLength, MethodLength, ClassLength
begin
require 'nokogiri'
rescue LoadError => le
$stderr.puts "LoadError: #{le.message}"
$stderr.puts 'Run: gem install nokogiri'
exit
end
# Headless HTML Editor. Edit HTML files programmatically.
class HeadlessHtmlEditor
attr_reader :dom
# Create a new Headless HTML Editor.
def initialize(input_file_name, input_encoding = 'utf-8')
@input_file_name = input_file_name
if File.file?(input_file_name) && File.fnmatch?('**.html', input_file_name)
# read html file
puts "R: #{input_file_name}"
@dom = Nokogiri::HTML(
open(input_file_name, "r:#{input_encoding}", universal_newline: false)
)
end
end
UNWANTED_CLASSES = %w{MsoNormal MsoBodyText NormalBold MsoTitle MsoHeader Templatehelp
TOCEntry Indent1 MsoCaption MsoListParagraph
MsoNormalTable MsoTableGrid MsoTableClassic1
MsoListParagraphCxSpFirst MsoListParagraphCxSpMiddle MsoListParagraphCxSpLast
MsoCommentText msocomtxt msocomoff MsoEndnoteText MsoFootnoteText}
# Cleanup after MS Word.
def remove_word_artifacts(options = { rebuild_toc: true })
@dom.css('meta[name="Generator"]').remove
# Remove abandoned anchors, that are not linked to.
@dom.css('a[name]').each do |a|
if @dom.css('a[href="#' + a['name'] + '"]').size == 0
puts "<a name=\"#{a['name']}\"> was removed, because it had no links to it."
a.replace(a.inner_html)
end
end
# Clean up h1-h6 tags
headings = @dom.css('h1, h2, h3, h4, h5, h6')
headings.each do |heading|
a = heading.at_css('a[name]')
if a
heading['id'] = a['name'].sub(/_Toc/, 'Toc')
a.replace(a.inner_html)
end
heading.inner_html = heading.inner_html.sub(/\A(\s*\d+\.?)+\uC2A0*/, '').strip
end
# Remove Words "normal" classes.
UNWANTED_CLASSES.each do |class_name|
@dom.css(".#{class_name}").each do |node|
node.remove_attribute('class')
end
end
# Remove unwanted section tags
@dom.css('.WordSection1, .WordSection2, .WordSection3, .WordSection4, .WordSection5, .WordSection6, .WordSection7, .WordSection8').each do |section|
puts "Removing #{section.name}.#{section['class']}"
section.replace(section.inner_html)
end
if options[:rebuild_toc]
# Remove page numbers from TOC
@dom.css('.MsoToc1 a, .MsoToc2 a, .MsoToc3 a, .MsoToc4 a').each do |item|
item.inner_html = item.inner_text.sub(/\A(\d+\.)+/, '').sub(/(\s+\d+)\Z/, '').strip
end
# Rewrite Toc as ordered list.
toc_item = @dom.at_css('.MsoToc1')
previous_toc_level = 0
new_toc = []
while toc_item
toc_item.inner_html = toc_item.inner_html.sub(/\n/, ' ')
class_attr = toc_item.attr('class')
current_toc_level = class_attr[6].to_i
new_toc << "</li>\n" if previous_toc_level == current_toc_level
new_toc << "</ol>\n</li>\n" if previous_toc_level > current_toc_level
new_toc << "\n<ol#{' id="toc"' if previous_toc_level == 0}>\n" if previous_toc_level < current_toc_level
link = toc_item.at_css('a')
if link.nil?
puts toc_item.to_s
else
toc_item.at_css('a').inner_html = link.inner_html.sub(/\A(\s*\d+)/, '').strip
new_toc << "<li>#{toc_item.inner_html.sub(/#_Toc/, '#Toc')}"
end
previous_toc_level = current_toc_level
begin
toc_item = toc_item.next_element
end while toc_item && toc_item.text?
toc_item = nil unless toc_item && toc_item.attr('class') && toc_item.attr('class').start_with?('MsoToc')
end
@dom.at_css('.MsoToc1').replace(new_toc.join('')) if @dom.at_css('.MsoToc1')
# Remove old Table of Contents
@dom.css('.MsoToc1, .MsoToc2, .MsoToc3, .MsoToc4').each { |item| item.remove }
end
# Remove empty paragraphs
@dom.css('p').each do |p|
if p.content.gsub("\uC2A0", '').strip.size == 0 && !p.at_css('img')
puts 'Removing empty paragraph.'
p.remove
end
end
@dom.css('table + br').remove
# /<!--\[if[.\n\r]+\[endif\]\s*-->/
end
# Remove script tags from the header
def remove_header_scripts
@dom.css('head script').remove
end
# Remove ins and del tags added by MS Words Change Tracking.
def accept_word_changes_tracked
@dom.css('del').remove
@dom.css('ins').each do |ins|
ins.replace ins.inner_html
end
end
# Change h1 to h2 and so on. h6 is not changed, so its a potential mess.
def demote_headings
@dom.css('h1, h2, h3, h4, h5').each do |heading|
heading.name = "h#{heading.name[1].to_i + 1}"
end
end
def remove_break_after_block
block_tags = %w{h1 h2 h3 h4 h5 h6 p div table}
@dom.css(block_tags.join(' + br, ') + ' + br').remove
end
# Save the file with the same file name.
def save!(output_encoding = 'utf-8')
save_as!(@input_file_name, output_encoding)
end
# Save file with a new file name.
def save_as!(output_file_name, output_encoding = 'utf-8')
puts "W: #{output_file_name}"
begin
if File.writable?(output_file_name) || !File.exists?(output_file_name)
File.open(output_file_name, "w:#{output_encoding}", universal_newline: false) do |f|
f.write @dom.to_html(encoding: output_encoding, indent: 2)
end
else
$stderr.puts 'Failed: Read only!'
end
rescue StandardError => se
$stderr.puts "\nFailed!\n#{se.message}"
end
end
# Edit all HTML files in a folder.
def self.edit_folder(folder, &block)
Dir.open(folder.gsub(/\\/, '/')) do |d|
d.each do |file_name|
file_name = File.join(d.path, file_name)
if File.file? file_name
editor = new(file_name)
unless editor.dom.nil?
yield editor
editor.save!
end
end
end
end
end
# Edit files listed in a text file. File names are absolute.
# If the first character on a line is # the line is ignored.
def self.bulk_edit(file_list_file_name, &block)
txt_file_name = File.expand_path(file_list_file_name)
File.readlines(txt_file_name).each do |file_name|
unless file_name.start_with? '#'
# Strip added to remove trailing newline characters.
file_name.strip!
if File.file? file_name
editor = new(file_name)
if editor.dom.nil?
puts "No DOM found in #{file_name}."
else
yield editor
editor.save!
end
end
end
end
end
end
if __FILE__ == $PROGRAM_NAME
HeadlessHtmlEditor.edit_folder(File.expand_path(ARGV[0])) do |editor|
editor.dom.at_css('html').add_child '<!-- HeadlessHtmlEditor was here! -->'
end
end
Made file names case insensitive.
#!/usr/bin/env ruby
# coding: utf-8
# rubocop:disable LineLength, MethodLength, ClassLength
begin
require 'nokogiri'
rescue LoadError => le
$stderr.puts "LoadError: #{le.message}"
$stderr.puts 'Run: gem install nokogiri'
exit
end
# Headless HTML Editor. Edit HTML files programmatically.
class HeadlessHtmlEditor
attr_reader :dom
# Create a new Headless HTML Editor.
def initialize(input_file_name, input_encoding = 'utf-8')
@input_file_name = input_file_name
if File.file?(input_file_name) && File.fnmatch?('**.html', input_file_name, File::FNM_CASEFOLD)
# read html file
puts "R: #{input_file_name}"
@dom = Nokogiri::HTML(
open(input_file_name, "r:#{input_encoding}", universal_newline: false)
)
end
end
UNWANTED_CLASSES = %w{MsoNormal MsoBodyText NormalBold MsoTitle MsoHeader Templatehelp
TOCEntry Indent1 MsoCaption MsoListParagraph
MsoNormalTable MsoTableGrid MsoTableClassic1
MsoListParagraphCxSpFirst MsoListParagraphCxSpMiddle MsoListParagraphCxSpLast
MsoCommentText msocomtxt msocomoff MsoEndnoteText MsoFootnoteText}
# Cleanup after MS Word.
def remove_word_artifacts(options = { rebuild_toc: true })
@dom.css('meta[name="Generator"]').remove
# Remove abandoned anchors, that are not linked to.
@dom.css('a[name]').each do |a|
if @dom.css('a[href="#' + a['name'] + '"]').size == 0
puts "<a name=\"#{a['name']}\"> was removed, because it had no links to it."
a.replace(a.inner_html)
end
end
# Clean up h1-h6 tags
headings = @dom.css('h1, h2, h3, h4, h5, h6')
headings.each do |heading|
a = heading.at_css('a[name]')
if a
heading['id'] = a['name'].sub(/_Toc/, 'Toc')
a.replace(a.inner_html)
end
heading.inner_html = heading.inner_html.sub(/\A(\s*\d+\.?)+\uC2A0*/, '').strip
end
# Remove Words "normal" classes.
UNWANTED_CLASSES.each do |class_name|
@dom.css(".#{class_name}").each do |node|
node.remove_attribute('class')
end
end
# Remove unwanted section tags
@dom.css('.WordSection1, .WordSection2, .WordSection3, .WordSection4, .WordSection5, .WordSection6, .WordSection7, .WordSection8').each do |section|
puts "Removing #{section.name}.#{section['class']}"
section.replace(section.inner_html)
end
if options[:rebuild_toc]
# Remove page numbers from TOC
@dom.css('.MsoToc1 a, .MsoToc2 a, .MsoToc3 a, .MsoToc4 a').each do |item|
item.inner_html = item.inner_text.sub(/\A(\d+\.)+/, '').sub(/(\s+\d+)\Z/, '').strip
end
# Rewrite Toc as ordered list.
toc_item = @dom.at_css('.MsoToc1')
previous_toc_level = 0
new_toc = []
while toc_item
toc_item.inner_html = toc_item.inner_html.sub(/\n/, ' ')
class_attr = toc_item.attr('class')
current_toc_level = class_attr[6].to_i
new_toc << "</li>\n" if previous_toc_level == current_toc_level
new_toc << "</ol>\n</li>\n" if previous_toc_level > current_toc_level
new_toc << "\n<ol#{' id="toc"' if previous_toc_level == 0}>\n" if previous_toc_level < current_toc_level
link = toc_item.at_css('a')
if link.nil?
puts toc_item.to_s
else
toc_item.at_css('a').inner_html = link.inner_html.sub(/\A(\s*\d+)/, '').strip
new_toc << "<li>#{toc_item.inner_html.sub(/#_Toc/, '#Toc')}"
end
previous_toc_level = current_toc_level
begin
toc_item = toc_item.next_element
end while toc_item && toc_item.text?
toc_item = nil unless toc_item && toc_item.attr('class') && toc_item.attr('class').start_with?('MsoToc')
end
@dom.at_css('.MsoToc1').replace(new_toc.join('')) if @dom.at_css('.MsoToc1')
# Remove old Table of Contents
@dom.css('.MsoToc1, .MsoToc2, .MsoToc3, .MsoToc4').each { |item| item.remove }
end
# Remove empty paragraphs
@dom.css('p').each do |p|
if p.content.gsub("\uC2A0", '').strip.size == 0 && !p.at_css('img')
puts 'Removing empty paragraph.'
p.remove
end
end
@dom.css('table + br').remove
# /<!--\[if[.\n\r]+\[endif\]\s*-->/
end
# Remove script tags from the header
def remove_header_scripts
@dom.css('head script').remove
end
# Remove ins and del tags added by MS Words Change Tracking.
def accept_word_changes_tracked
@dom.css('del').remove
@dom.css('ins').each do |ins|
ins.replace ins.inner_html
end
end
# Change h1 to h2 and so on. h6 is not changed, so its a potential mess.
def demote_headings
@dom.css('h1, h2, h3, h4, h5').each do |heading|
heading.name = "h#{heading.name[1].to_i + 1}"
end
end
def remove_break_after_block
block_tags = %w{h1 h2 h3 h4 h5 h6 p div table}
@dom.css(block_tags.join(' + br, ') + ' + br').remove
end
# Save the file with the same file name.
def save!(output_encoding = 'utf-8')
save_as!(@input_file_name, output_encoding)
end
# Save file with a new file name.
def save_as!(output_file_name, output_encoding = 'utf-8')
puts "W: #{output_file_name}"
begin
if File.writable?(output_file_name) || !File.exists?(output_file_name)
File.open(output_file_name, "w:#{output_encoding}", universal_newline: false) do |f|
f.write @dom.to_html(encoding: output_encoding, indent: 2)
end
else
$stderr.puts 'Failed: Read only!'
end
rescue StandardError => se
$stderr.puts "\nFailed!\n#{se.message}"
end
end
# Edit all HTML files in a folder.
def self.edit_folder(folder, &block)
Dir.open(folder.gsub(/\\/, '/')) do |d|
d.each do |file_name|
file_name = File.join(d.path, file_name)
if File.file? file_name
editor = new(file_name)
unless editor.dom.nil?
yield editor
editor.save!
end
end
end
end
end
# Edit files listed in a text file. File names are absolute.
# If the first character on a line is # the line is ignored.
def self.bulk_edit(file_list_file_name, &block)
txt_file_name = File.expand_path(file_list_file_name)
File.readlines(txt_file_name).each do |file_name|
unless file_name.start_with? '#'
# Strip added to remove trailing newline characters.
file_name.strip!
if File.file? file_name
editor = new(file_name)
if editor.dom.nil?
puts "No DOM found in #{file_name}."
else
yield editor
editor.save!
end
end
end
end
end
end
if __FILE__ == $PROGRAM_NAME
HeadlessHtmlEditor.edit_folder(File.expand_path(ARGV[0])) do |editor|
editor.dom.at_css('html').add_child '<!-- HeadlessHtmlEditor was here! -->'
end
end
|
module ActiveScaffold
module Helpers
# All extra helpers that should be included in the View.
# Also a dumping ground for uncategorized helpers.
module ViewHelpers
include ActiveScaffold::Helpers::Ids
include ActiveScaffold::Helpers::Associations
include ActiveScaffold::Helpers::Pagination
include ActiveScaffold::Helpers::ListColumns
include ActiveScaffold::Helpers::FormColumns
##
## Delegates
##
# access to the configuration variable
def active_scaffold_config
@controller.class.active_scaffold_config
end
def active_scaffold_config_for(*args)
@controller.class.active_scaffold_config_for(*args)
end
def active_scaffold_controller_for(*args)
@controller.class.active_scaffold_controller_for(*args)
end
##
## Uncategorized
##
def generate_temporary_id
(Time.now.to_f*1000).to_i.to_s
end
# Turns [[label, value]] into <option> tags
# Takes optional parameter of :include_blank
def option_tags_for(select_options, options = {})
select_options.insert(0,[as_('- select -'),nil]) if options[:include_blank]
select_options.collect do |option|
label, value = option[0], option[1]
value.nil? ? "<option value="">#{label}</option>" : "<option value=\"#{value}\">#{label}</option>"
end
end
# Should this column be displayed in the subform?
def in_subform?(column, parent_record)
return true unless column.association
# Polymorphic associations can't appear because they *might* be the reverse association, and because you generally don't assign an association from the polymorphic side ... I think.
return false if column.polymorphic_association?
# We don't have the UI to currently handle habtm in subforms
return false if column.association.macro == :has_and_belongs_to_many
# A column shouldn't be in the subform if it's the reverse association to the parent
return false if column.association.reverse_for?(parent_record.class)
#return false if column.association.klass == parent_record.class
return true
end
def form_remote_upload_tag(url_for_options = {}, options = {})
output=""
output << "<iframe id='#{action_iframe_id(url_for_options)}' name='#{action_iframe_id(url_for_options)}' style='display:none'></iframe>"
options[:form] = true
options ||= {}
onsubmits = options[:onsubmit] ? [ options[:onsubmit] ] : [ ]
onsubmits << "setTimeout(function() { #{options[:loading]} }, 10); "
# the setTimeout prevents the Form.disable from being called before the submit. If that occurs, then no data will be posted.
onsubmits << "return true"
# simulate a "loading"
options[:onsubmit] = onsubmits * ';'
options[:target] = action_iframe_id(url_for_options)
options[:multipart] = true
output << form_tag(url_for_options, options)
end
# easy way to include ActiveScaffold assets
def active_scaffold_includes
js = ActiveScaffold::Config::Core.javascripts.collect do |name|
javascript_include_tag(ActiveScaffold::Config::Core.asset_path(:javascript, name))
end.join('')
css = stylesheet_link_tag(ActiveScaffold::Config::Core.asset_path(:stylesheet, "stylesheet.css"))
ie_css = stylesheet_link_tag(ActiveScaffold::Config::Core.asset_path(:stylesheet, "stylesheet-ie.css"))
js + "\n" + css + "\n<!--[if IE]>" + ie_css + "<![endif]-->\n"
end
# a general-use loading indicator (the "stuff is happening, please wait" feedback)
def loading_indicator_tag(options)
image_tag "/images/active_scaffold/default/indicator.gif", :style => "visibility:hidden;", :id => loading_indicator_id(options), :alt => "loading indicator", :class => "loading-indicator"
end
def params_for(options = {})
# :adapter and :position are one-use rendering arguments. they should not propagate.
# :sort, :sort_direction, and :page are arguments that stored in the session. they need not propagate.
# and wow. no we don't want to propagate :record.
# :commit is a special rails variable for form buttons
blacklist = [:adapter, :position, :sort, :sort_direction, :page, :record, :commit, :_method]
unless @params_for
@params_for = params.clone.delete_if { |key, value| blacklist.include? key.to_sym if key }
@params_for[:controller] = '/' + @params_for[:controller] unless @params_for[:controller].first(1) == '/' # for namespaced controllers
@params_for.delete(:id) if @params_for[:id].nil?
end
@params_for.merge(options)
end
# Creates a javascript-based link that toggles the visibility of some element on the page.
# By default, it toggles the visibility of the sibling after the one it's nested in. You may pass custom javascript logic in options[:of] to change that, though. For example, you could say :of => '$("my_div_id")'.
# You may also flag whether the other element is visible by default or not, and the initial text will adjust accordingly.
def link_to_visibility_toggle(options = {})
options[:of] ||= '$(this.parentNode).next()'
options[:default_visible] = true if options[:default_visible].nil?
link_text = options[:default_visible] ? 'hide' : 'show'
link_to_function as_(link_text), "e = #{options[:of]}; e.toggle(); this.innerHTML = (e.style.display == 'none') ? '#{as_('show')}' : '#{as_('hide')}'", :class => 'visibility-toggle'
end
def render_action_link(link, url_options)
url_options = url_options.clone
url_options[:action] = link.action
url_options.merge! link.parameters if link.parameters
# NOTE this is in url_options instead of html_options on purpose. the reason is that the client-side
# action link javascript needs to submit the proper method, but the normal html_options[:method]
# argument leaves no way to extract the proper method from the rendered tag.
url_options[:_method] = link.method
# Needs to be in html_options to as the adding _method to the url is no longer supported by Rails
html_options[:method] = link.method
html_options = {:class => link.action}
html_options[:confirm] = link.confirm if link.confirm?
html_options[:position] = link.position if link.position and link.inline?
html_options[:class] += ' action' if link.inline?
html_options[:popup] = true if link.popup?
html_options[:id] = action_link_id(url_options[:action],url_options[:id])
if link.dhtml_confirm?
html_options[:class] += ' action' if !link.inline?
html_options[:page_link] = 'true' if !link.inline?
html_options[:dhtml_confirm] = link.dhtml_confirm.value
html_options[:onclick] = link.dhtml_confirm.onclick_function(controller,action_link_id(url_options[:action],url_options[:id]))
end
link_to link.label, url_options, html_options
end
def column_class(column, column_value)
classes = []
classes << "#{column.name}-column"
classes << column.css_class unless column.css_class.nil?
classes << 'empty' if column_empty? column_value
classes << 'sorted' if active_scaffold_config.list.user.sorting.sorts_on?(column)
classes << 'numeric' if column.column and [:decimal, :float, :integer].include?(column.column.type)
classes.join(' ')
end
def column_empty?(column_value)
column_value.nil? || (column_value.empty? rescue false)
end
def column_calculation(column)
calculation = active_scaffold_config.model.calculate(column.calculate, column.name, :conditions => controller.send(:all_conditions), :include => controller.send(:active_scaffold_joins))
end
end
end
end
added :method to html_options as well as url_options to support latest Rails, part 2
module ActiveScaffold
module Helpers
# All extra helpers that should be included in the View.
# Also a dumping ground for uncategorized helpers.
module ViewHelpers
include ActiveScaffold::Helpers::Ids
include ActiveScaffold::Helpers::Associations
include ActiveScaffold::Helpers::Pagination
include ActiveScaffold::Helpers::ListColumns
include ActiveScaffold::Helpers::FormColumns
##
## Delegates
##
# access to the configuration variable
def active_scaffold_config
@controller.class.active_scaffold_config
end
def active_scaffold_config_for(*args)
@controller.class.active_scaffold_config_for(*args)
end
def active_scaffold_controller_for(*args)
@controller.class.active_scaffold_controller_for(*args)
end
##
## Uncategorized
##
def generate_temporary_id
(Time.now.to_f*1000).to_i.to_s
end
# Turns [[label, value]] into <option> tags
# Takes optional parameter of :include_blank
def option_tags_for(select_options, options = {})
select_options.insert(0,[as_('- select -'),nil]) if options[:include_blank]
select_options.collect do |option|
label, value = option[0], option[1]
value.nil? ? "<option value="">#{label}</option>" : "<option value=\"#{value}\">#{label}</option>"
end
end
# Should this column be displayed in the subform?
def in_subform?(column, parent_record)
return true unless column.association
# Polymorphic associations can't appear because they *might* be the reverse association, and because you generally don't assign an association from the polymorphic side ... I think.
return false if column.polymorphic_association?
# We don't have the UI to currently handle habtm in subforms
return false if column.association.macro == :has_and_belongs_to_many
# A column shouldn't be in the subform if it's the reverse association to the parent
return false if column.association.reverse_for?(parent_record.class)
#return false if column.association.klass == parent_record.class
return true
end
def form_remote_upload_tag(url_for_options = {}, options = {})
output=""
output << "<iframe id='#{action_iframe_id(url_for_options)}' name='#{action_iframe_id(url_for_options)}' style='display:none'></iframe>"
options[:form] = true
options ||= {}
onsubmits = options[:onsubmit] ? [ options[:onsubmit] ] : [ ]
onsubmits << "setTimeout(function() { #{options[:loading]} }, 10); "
# the setTimeout prevents the Form.disable from being called before the submit. If that occurs, then no data will be posted.
onsubmits << "return true"
# simulate a "loading"
options[:onsubmit] = onsubmits * ';'
options[:target] = action_iframe_id(url_for_options)
options[:multipart] = true
output << form_tag(url_for_options, options)
end
# easy way to include ActiveScaffold assets
def active_scaffold_includes
js = ActiveScaffold::Config::Core.javascripts.collect do |name|
javascript_include_tag(ActiveScaffold::Config::Core.asset_path(:javascript, name))
end.join('')
css = stylesheet_link_tag(ActiveScaffold::Config::Core.asset_path(:stylesheet, "stylesheet.css"))
ie_css = stylesheet_link_tag(ActiveScaffold::Config::Core.asset_path(:stylesheet, "stylesheet-ie.css"))
js + "\n" + css + "\n<!--[if IE]>" + ie_css + "<![endif]-->\n"
end
# a general-use loading indicator (the "stuff is happening, please wait" feedback)
def loading_indicator_tag(options)
image_tag "/images/active_scaffold/default/indicator.gif", :style => "visibility:hidden;", :id => loading_indicator_id(options), :alt => "loading indicator", :class => "loading-indicator"
end
def params_for(options = {})
# :adapter and :position are one-use rendering arguments. they should not propagate.
# :sort, :sort_direction, and :page are arguments that stored in the session. they need not propagate.
# and wow. no we don't want to propagate :record.
# :commit is a special rails variable for form buttons
blacklist = [:adapter, :position, :sort, :sort_direction, :page, :record, :commit, :_method]
unless @params_for
@params_for = params.clone.delete_if { |key, value| blacklist.include? key.to_sym if key }
@params_for[:controller] = '/' + @params_for[:controller] unless @params_for[:controller].first(1) == '/' # for namespaced controllers
@params_for.delete(:id) if @params_for[:id].nil?
end
@params_for.merge(options)
end
# Creates a javascript-based link that toggles the visibility of some element on the page.
# By default, it toggles the visibility of the sibling after the one it's nested in. You may pass custom javascript logic in options[:of] to change that, though. For example, you could say :of => '$("my_div_id")'.
# You may also flag whether the other element is visible by default or not, and the initial text will adjust accordingly.
def link_to_visibility_toggle(options = {})
options[:of] ||= '$(this.parentNode).next()'
options[:default_visible] = true if options[:default_visible].nil?
link_text = options[:default_visible] ? 'hide' : 'show'
link_to_function as_(link_text), "e = #{options[:of]}; e.toggle(); this.innerHTML = (e.style.display == 'none') ? '#{as_('show')}' : '#{as_('hide')}'", :class => 'visibility-toggle'
end
def render_action_link(link, url_options)
url_options = url_options.clone
url_options[:action] = link.action
url_options.merge! link.parameters if link.parameters
# NOTE this is in url_options instead of html_options on purpose. the reason is that the client-side
# action link javascript needs to submit the proper method, but the normal html_options[:method]
# argument leaves no way to extract the proper method from the rendered tag.
url_options[:_method] = link.method
html_options = {:class => link.action}
# Needs to be in html_options to as the adding _method to the url is no longer supported by Rails
html_options[:method] = link.method
html_options[:confirm] = link.confirm if link.confirm?
html_options[:position] = link.position if link.position and link.inline?
html_options[:class] += ' action' if link.inline?
html_options[:popup] = true if link.popup?
html_options[:id] = action_link_id(url_options[:action],url_options[:id])
if link.dhtml_confirm?
html_options[:class] += ' action' if !link.inline?
html_options[:page_link] = 'true' if !link.inline?
html_options[:dhtml_confirm] = link.dhtml_confirm.value
html_options[:onclick] = link.dhtml_confirm.onclick_function(controller,action_link_id(url_options[:action],url_options[:id]))
end
link_to link.label, url_options, html_options
end
def column_class(column, column_value)
classes = []
classes << "#{column.name}-column"
classes << column.css_class unless column.css_class.nil?
classes << 'empty' if column_empty? column_value
classes << 'sorted' if active_scaffold_config.list.user.sorting.sorts_on?(column)
classes << 'numeric' if column.column and [:decimal, :float, :integer].include?(column.column.type)
classes.join(' ')
end
def column_empty?(column_value)
column_value.nil? || (column_value.empty? rescue false)
end
def column_calculation(column)
calculation = active_scaffold_config.model.calculate(column.calculate, column.name, :conditions => controller.send(:all_conditions), :include => controller.send(:active_scaffold_joins))
end
end
end
end |
require 'oauth2'
module Hieraviz
class AuthGitlab
def initialize(settings)
if settings['proxy_uri']
@@client ||= OAuth2::Client.new(
settings['application_id'],
settings['secret'],
:site => settings['host'],
connection_opts: {
:proxy => {
:uri => settings['proxy_uri']
}
}
)
else
@@client ||= OAuth2::Client.new(
settings['application_id'],
settings['secret'],
:site => settings['host']
)
end
@settings = settings
end
def access_token(request, code)
@@client.auth_code.get_token(code, :redirect_uri => redirect_uri(request.url))
end
def get_response(url, token)
a_token = OAuth2::AccessToken.new(@@client, token)
begin
JSON.parse(a_token.get(url).body)
rescue Exception => e
{ 'error' => JSON.parse(e.message.split(/\n/)[1])['message'] }
end
end
def redirect_uri(url)
uri = URI.parse(url)
uri.path = '/logged-in'
uri.query = nil
uri.fragment = nil
uri.to_s
end
def login_url(request)
@@client.auth_code.authorize_url(:redirect_uri => redirect_uri(request.url))
end
def authorized?(token)
if @settings['resource_required']
resp = get_response(@settings['resource_required'], token)
if resp['error'] ||
(resp[@settings['required_response_key']] &&
resp[@settings['required_response_key']] != resp[@settings['required_response_value']])
false
else
true
end
end
true
end
def user_info(token)
get_response('/api/v3/user', token)
end
end
end
actually faraday takes proxy setting from env
require 'oauth2'
module Hieraviz
class AuthGitlab
def initialize(settings)
@@client ||= OAuth2::Client.new(
settings['application_id'],
settings['secret'],
:site => settings['host']
)
@settings = settings
end
def access_token(request, code)
@@client.auth_code.get_token(code, :redirect_uri => redirect_uri(request.url))
end
def get_response(url, token)
a_token = OAuth2::AccessToken.new(@@client, token)
begin
JSON.parse(a_token.get(url).body)
rescue Exception => e
{ 'error' => JSON.parse(e.message.split(/\n/)[1])['message'] }
end
end
def redirect_uri(url)
uri = URI.parse(url)
uri.path = '/logged-in'
uri.query = nil
uri.fragment = nil
uri.to_s
end
def login_url(request)
@@client.auth_code.authorize_url(:redirect_uri => redirect_uri(request.url))
end
def authorized?(token)
if @settings['resource_required']
resp = get_response(@settings['resource_required'], token)
if resp['error'] ||
(resp[@settings['required_response_key']] &&
resp[@settings['required_response_key']] != resp[@settings['required_response_value']])
false
else
true
end
end
true
end
def user_info(token)
get_response('/api/v3/user', token)
end
end
end
|
# frozen_string_literal: true
module HTMLProofer
VERSION = '3.18.0'
end
:gem: bump to 3.18.1
# frozen_string_literal: true
module HTMLProofer
VERSION = '3.18.1'
end
|
module HttpObjects
VERSION = "0.0.2pre"
end
Releasing version 0.0.2
module HttpObjects
VERSION = "0.0.2"
end
|
Pod::Spec.new do |spec|
spec.name = "EstimoteFleetManagementSDK"
spec.version = "4.31.2"
spec.summary = "iOS library for managing Estimote Beacons."
spec.homepage = "https://github.com/Estimote/iOS-Fleet-Management-SDK"
spec.license = { type: "Apache 2.0", file: "LICENSE" }
spec.authors = { "Estimote, Inc" => "contact@estimote.com" }
spec.source = { git: "https://github.com/Estimote/iOS-Fleet-Management-SDK.git", tag: spec.version }
spec.social_media_url = "https://twitter.com/estimote"
spec.platform = :ios
spec.vendored_frameworks = "EstimoteFleetManagementSDK/EstimoteFleetManagementSDK.framework"
spec.ios.deployment_target = "10.0"
end
Updated podspec.
Pod::Spec.new do |spec|
spec.name = "EstimoteFleetManagementSDK"
spec.version = "4.32.2"
spec.summary = "iOS library for managing Estimote Beacons."
spec.homepage = "https://github.com/Estimote/iOS-Fleet-Management-SDK"
spec.license = { type: "Apache 2.0", file: "LICENSE" }
spec.authors = { "Estimote, Inc" => "contact@estimote.com" }
spec.source = { git: "https://github.com/Estimote/iOS-Fleet-Management-SDK.git", tag: spec.version }
spec.social_media_url = "https://twitter.com/estimote"
spec.platform = :ios
spec.vendored_frameworks = "EstimoteFleetManagementSDK/EstimoteFleetManagementSDK.framework"
spec.ios.deployment_target = "11.0"
end
|
class ImportExportHelper
DEBUG=true
EXPORT_DIR="tmp/frab_export"
def initialize(conference=nil)
@export_dir = EXPORT_DIR
@conference = conference
PaperTrail.enabled = false
end
# everything except: RecentChanges
def run_export
if @conference.nil?
puts "[!] the conference wasn't found."
exit
end
FileUtils.mkdir_p(@export_dir)
ActiveRecord::Base.transaction do
dump "conference", @conference
dump "conference_tracks", @conference.tracks
dump "conference_cfp", @conference.call_for_papers
dump "conference_ticket_server", @conference.ticket_server
dump "conference_rooms", @conference.rooms
dump "conference_days", @conference.days
dump "conference_languages", @conference.languages
events = dump "events", @conference.events
dump_has_many "tickets", @conference.events, 'ticket'
dump_has_many "event_people", @conference.events, 'event_people'
dump_has_many "event_feedbacks", @conference.events, 'event_feedbacks'
people = dump_has_many "people", @conference.events, 'people'
dump_has_many "event_links", @conference.events, 'links'
attachments = dump_has_many "event_attachments", @conference.events, 'event_attachments'
dump_has_many "event_ratings", @conference.events, 'event_ratings'
dump_has_many "conflicts", @conference.events, 'conflicts'
#dump_has_many "conflicts_as_conflicting", @conference.events, 'conflicts_as_conflicting'
dump_has_many "people_phone_numbers", people, 'phone_numbers'
dump_has_many "people_im_accounts", people, 'im_accounts'
dump_has_many "people_links", people, 'links'
dump_has_many "people_languages", people, 'languages'
dump_has_many "people_availabilities", people, 'availabilities'
dump_has_many "users", people, 'user'
# TODO languages
# TODO videos
# TODO notifications
export_paperclip_files(events, people, attachments)
end
end
def run_import(export_dir=EXPORT_DIR)
@export_dir = export_dir
unless File.directory? @export_dir
puts "Directory #{@export_dir} does not exist!"
exit
end
disable_callbacks
# old => new
@mappings = {
conference: {}, tracks: {}, cfp: {}, rooms: {}, days: {},
people: {}, users: {},
events: {},
people_user: {}
}
ActiveRecord::Base.transaction do
unpack_paperclip_files
restore_all_data
end
end
private
def restore_all_data
restore("conference", Conference) do |id, c|
test = Conference.find_by_acronym(c.acronym)
if test
puts "conference #{c} already exists!"
exit
end
puts " #{c}" if DEBUG
c.save!
@mappings[:conference][id] = c.id
@conference_id = c.id
end
restore_conference_data
restore_multiple("people", Person) do |id, obj|
person = Person.find_by_email(obj.email)
if person
# don't create a new person
@mappings[:people][id] = person.id
@mappings[:people_user][person.user_id] = person
else
if (file = import_file("avatars", id, obj.avatar_file_name))
obj.avatar = file
end
obj.save!
@mappings[:people][id] = obj.id
@mappings[:people_user][obj.user_id] = obj
end
end
restore_users do |id, yaml, obj|
user = User.find_by_email(obj.email)
if user
# don't create a new user
@mappings[:users][id] = user.id
else
%w{ confirmation_sent_at confirmation_token confirmed_at created_at
current_sign_in_at current_sign_in_ip last_sign_in_at
last_sign_in_ip password_digest pentabarf_password
pentabarf_salt remember_created_at remember_token
reset_password_token role sign_in_count updated_at
}.each { |var|
obj.send("#{var}=",yaml[var])
}
obj.call_for_papers_id = @mappings[:cfp][obj.call_for_papers_id]
obj.confirmed_at ||= Time.now
obj.person = @mappings[:people_user][id]
obj.save!
@mappings[:users][id] = obj.id
end
end
restore_multiple("events", Event) do |id, obj|
obj.conference_id = @conference_id
obj.track_id = @mappings[:tracks][obj.track_id]
obj.room_id = @mappings[:rooms][obj.room_id]
if (file = import_file("logos", id, obj.logo_file_name))
obj.logo = file
end
obj.save!
@mappings[:events][id] = obj.id
end
# uses mappings: events, people
restore_events_data
# uses mappings: people, days
restore_people_data
update_counters
# TODO update_conflicts
end
def restore_conference_data
restore_multiple("conference_tracks", Track) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:tracks][id] = obj.id
end
restore("conference_cfp", CallForPapers) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:cfp][id] = obj.id
end
restore("conference_ticket_server", TicketServer) do |id, obj|
obj.conference_id = @conference_id
obj.save!
end
restore_multiple("conference_rooms", Room) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:rooms][id] = obj.id
end
restore_multiple("conference_days", Day) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:days][id] = obj.id
end
restore_multiple("conference_languages", Language) do |id, obj|
obj.attachable_id = @conference_id
obj.save!
end
end
def restore_events_data
restore_multiple("tickets", Ticket) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.save!
end
restore_multiple("event_people", EventPerson) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.person_id = @mappings[:people][obj.person_id]
obj.save!
end
restore_multiple("event_feedbacks", EventFeedback) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.save!
end
restore_multiple("event_ratings", EventRating) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.person_id = @mappings[:people][obj.person_id]
obj.save! if obj.valid?
end
restore_multiple("event_links", Link) do |id, obj|
obj.linkable_id = @mappings[:events][obj.linkable_id]
obj.save!
end
restore_multiple("event_attachments", EventAttachment) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
if (file = import_file("attachments", id, obj.attachment_file_name))
obj.attachment = file
end
obj.save!
end
restore_multiple("conflicts", Conflict) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
if obj.conflicting_event_id
obj.conflicting_event_id = @mappings[:events][obj.conflicting_event_id]
end
obj.save!
end
end
def restore_people_data
restore_multiple("people_phone_numbers", PhoneNumber) do |id, obj|
new_id = @mappings[:people][obj.person_id]
test = PhoneNumber.where(person_id: new_id, phone_number: obj.phone_number)
unless test
obj.person_id = new_id
obj.save!
end
end
restore_multiple("people_im_accounts", ImAccount) do |id, obj|
new_id = @mappings[:people][obj.person_id]
test = ImAccount.where(person_id: new_id, im_address: obj.im_address)
unless test
obj.person_id = new_id
obj.save!
end
end
restore_multiple("people_links", Link) do |id, obj|
new_id = @mappings[:people][obj.linkable_id]
test = Link.where(linkable_id: new_id, linkable_type: obj.linkable_type,
url: obj.url)
unless test
obj.linkable_id = new_id
obj.save!
end
end
restore_multiple("people_languages", Language) do |id, obj|
new_id = @mappings[:people][obj.attachable_id]
test = Language.where(attachable_id: new_id, attachable_type: obj.attachable_type,
code: obj.code)
unless test
obj.attachable_id = new_id
obj.save!
end
end
restore_multiple("people_availabilities", Availability) do |id, obj|
next if obj.nil? or obj.start_date.nil? or obj.end_date.nil?
obj.conference_id = @conference_id
obj.person_id = @mappings[:people][obj.person_id]
obj.day_id = @mappings[:days][obj.day_id]
obj.save!
end
end
def dump_has_many(name, obj, attr)
arr = obj.collect { |t| t.send(attr) }
.flatten.select { |t| not t.nil? }.sort.uniq
dump name, arr
end
def dump(name,obj)
return if obj.nil?
File.open(File.join(@export_dir, name) + '.yaml', 'w') { |f|
if obj.respond_to?("collect")
f.puts obj.collect {|record| record.attributes}.to_yaml
else
f.puts obj.attributes.to_yaml
end
}
return obj
end
def restore(name, obj)
puts "[ ] restore #{name}" if DEBUG
file = File.join(@export_dir, name) + '.yaml'
return unless File.readable? file
records = YAML.load_file(file)
tmp = obj.new(records)
yield records['id'], tmp
end
def restore_multiple(name, obj)
puts "[ ] restore all #{name}" if DEBUG
records = YAML.load_file(File.join(@export_dir, name) + '.yaml')
records.each do |record|
tmp = obj.new(record)
yield record['id'], tmp
end
end
def restore_users(name="users", obj=User)
puts "[ ] restore all #{name}" if DEBUG
records = YAML.load_file(File.join(@export_dir, name) + '.yaml')
records.each do |record|
tmp = obj.new(record)
yield record['id'], record, tmp
end
end
def export_paperclip_files(events,people,attachments)
out_path = File.join(@export_dir, 'attachments.tar.gz')
paths = []
paths << events.select { |e| not e.logo.path.nil? }.collect { |e| e.logo.path.gsub(/^#{Rails.root}\//,'') }
paths << people.select { |e| not e.avatar.path.nil? }.collect { |e| e.avatar.path.gsub(/^#{Rails.root}\//,'') }
paths << attachments.select { |e| not e.attachment.path.nil? }.collect { |e| e.attachment.path.gsub(/^#{Rails.root}\//,'') }
paths.flatten!
# TODO don't use system
system( 'tar', *['-cpz', '-f', out_path, paths].flatten )
end
def import_file(dir, id, file_name)
return if file_name.nil? or file_name.empty?
path = File.join(@export_dir, 'public/system', dir, id.to_s, 'original', file_name)
if (File.readable?(path))
return File.open(path, 'r')
end
return
end
def unpack_paperclip_files()
path = File.join(@export_dir, 'attachments.tar.gz')
system( 'tar', *['-xz', '-f', path, '-C', @export_dir].flatten )
end
def disable_callbacks
EventPerson.skip_callback(:save, :after, :update_speaker_count)
Event.skip_callback(:save, :after, :update_conflicts)
Availability.skip_callback(:save, :after, :update_event_conflicts)
EventRating.skip_callback(:save, :after, :update_average)
EventFeedback.skip_callback(:save, :after, :update_average)
end
def update_counters
ActiveRecord::Base.connection.execute("UPDATE events SET speaker_count=(SELECT count(*) FROM event_people WHERE events.id=event_people.event_id AND event_people.event_role='speaker')")
update_event_average("event_ratings", "average_rating")
update_event_average("event_feedbacks", "average_feedback")
end
def update_event_average(table, field)
ActiveRecord::Base.connection.execute "UPDATE events SET #{field}=(
SELECT sum(rating)/count(rating)
FROM #{table} WHERE events.id = #{table}.event_id)"
end
end
fix import: user without person problem, due to several persons sharing an email
class ImportExportHelper
DEBUG=true
EXPORT_DIR="tmp/frab_export"
def initialize(conference=nil)
@export_dir = EXPORT_DIR
@conference = conference
PaperTrail.enabled = false
end
# everything except: RecentChanges
def run_export
if @conference.nil?
puts "[!] the conference wasn't found."
exit
end
FileUtils.mkdir_p(@export_dir)
ActiveRecord::Base.transaction do
dump "conference", @conference
dump "conference_tracks", @conference.tracks
dump "conference_cfp", @conference.call_for_papers
dump "conference_ticket_server", @conference.ticket_server
dump "conference_rooms", @conference.rooms
dump "conference_days", @conference.days
dump "conference_languages", @conference.languages
events = dump "events", @conference.events
dump_has_many "tickets", @conference.events, 'ticket'
dump_has_many "event_people", @conference.events, 'event_people'
dump_has_many "event_feedbacks", @conference.events, 'event_feedbacks'
people = dump_has_many "people", @conference.events, 'people'
dump_has_many "event_links", @conference.events, 'links'
attachments = dump_has_many "event_attachments", @conference.events, 'event_attachments'
dump_has_many "event_ratings", @conference.events, 'event_ratings'
dump_has_many "conflicts", @conference.events, 'conflicts'
#dump_has_many "conflicts_as_conflicting", @conference.events, 'conflicts_as_conflicting'
dump_has_many "people_phone_numbers", people, 'phone_numbers'
dump_has_many "people_im_accounts", people, 'im_accounts'
dump_has_many "people_links", people, 'links'
dump_has_many "people_languages", people, 'languages'
dump_has_many "people_availabilities", people, 'availabilities'
dump_has_many "users", people, 'user'
# TODO languages
# TODO videos
# TODO notifications
export_paperclip_files(events, people, attachments)
end
end
def run_import(export_dir=EXPORT_DIR)
@export_dir = export_dir
unless File.directory? @export_dir
puts "Directory #{@export_dir} does not exist!"
exit
end
disable_callbacks
# old => new
@mappings = {
conference: {}, tracks: {}, cfp: {}, rooms: {}, days: {},
people: {}, users: {},
events: {},
people_user: {}
}
ActiveRecord::Base.transaction do
unpack_paperclip_files
restore_all_data
end
end
private
def restore_all_data
restore("conference", Conference) do |id, c|
test = Conference.find_by_acronym(c.acronym)
if test
puts "conference #{c} already exists!"
exit
end
puts " #{c}" if DEBUG
c.save!
@mappings[:conference][id] = c.id
@conference_id = c.id
end
restore_conference_data
restore_multiple("people", Person) do |id, obj|
# TODO could be the wrong person if persons share email addresses!?
persons = Person.where(email: obj.email, public_name: obj.public_name)
person = persons.first
if person
# don't create a new person
@mappings[:people][id] = person.id
@mappings[:people_user][obj.user_id] = person
else
if (file = import_file("avatars", id, obj.avatar_file_name))
obj.avatar = file
end
obj.save!
@mappings[:people][id] = obj.id
@mappings[:people_user][obj.user_id] = obj
end
end
restore_users do |id, yaml, obj|
user = User.find_by_email(obj.email)
if user
# don't create a new user
@mappings[:users][id] = user.id
else
%w{ confirmation_sent_at confirmation_token confirmed_at created_at
current_sign_in_at current_sign_in_ip last_sign_in_at
last_sign_in_ip password_digest pentabarf_password
pentabarf_salt remember_created_at remember_token
reset_password_token role sign_in_count updated_at
}.each { |var|
obj.send("#{var}=",yaml[var])
}
obj.call_for_papers_id = @mappings[:cfp][obj.call_for_papers_id]
obj.confirmed_at ||= Time.now
obj.person = @mappings[:people_user][id]
unless obj.valid?
STDERR.puts "invalid user: #{id}"
p obj
p obj.errors.messages
else
obj.save!
@mappings[:users][id] = obj.id
end
end
end
restore_multiple("events", Event) do |id, obj|
obj.conference_id = @conference_id
obj.track_id = @mappings[:tracks][obj.track_id]
obj.room_id = @mappings[:rooms][obj.room_id]
if (file = import_file("logos", id, obj.logo_file_name))
obj.logo = file
end
obj.save!
@mappings[:events][id] = obj.id
end
# uses mappings: events, people
restore_events_data
# uses mappings: people, days
restore_people_data
update_counters
# TODO update_conflicts
end
def restore_conference_data
restore_multiple("conference_tracks", Track) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:tracks][id] = obj.id
end
restore("conference_cfp", CallForPapers) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:cfp][id] = obj.id
end
restore("conference_ticket_server", TicketServer) do |id, obj|
obj.conference_id = @conference_id
obj.save!
end
restore_multiple("conference_rooms", Room) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:rooms][id] = obj.id
end
restore_multiple("conference_days", Day) do |id, obj|
obj.conference_id = @conference_id
obj.save!
@mappings[:days][id] = obj.id
end
restore_multiple("conference_languages", Language) do |id, obj|
obj.attachable_id = @conference_id
obj.save!
end
end
def restore_events_data
restore_multiple("tickets", Ticket) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.save!
end
restore_multiple("event_people", EventPerson) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.person_id = @mappings[:people][obj.person_id]
obj.save!
end
restore_multiple("event_feedbacks", EventFeedback) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.save!
end
restore_multiple("event_ratings", EventRating) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
obj.person_id = @mappings[:people][obj.person_id]
obj.save! if obj.valid?
end
restore_multiple("event_links", Link) do |id, obj|
obj.linkable_id = @mappings[:events][obj.linkable_id]
obj.save!
end
restore_multiple("event_attachments", EventAttachment) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
if (file = import_file("attachments", id, obj.attachment_file_name))
obj.attachment = file
end
obj.save!
end
restore_multiple("conflicts", Conflict) do |id, obj|
obj.event_id = @mappings[:events][obj.event_id]
if obj.conflicting_event_id
obj.conflicting_event_id = @mappings[:events][obj.conflicting_event_id]
end
obj.save!
end
end
def restore_people_data
restore_multiple("people_phone_numbers", PhoneNumber) do |id, obj|
new_id = @mappings[:people][obj.person_id]
test = PhoneNumber.where(person_id: new_id, phone_number: obj.phone_number)
unless test
obj.person_id = new_id
obj.save!
end
end
restore_multiple("people_im_accounts", ImAccount) do |id, obj|
new_id = @mappings[:people][obj.person_id]
test = ImAccount.where(person_id: new_id, im_address: obj.im_address)
unless test
obj.person_id = new_id
obj.save!
end
end
restore_multiple("people_links", Link) do |id, obj|
new_id = @mappings[:people][obj.linkable_id]
test = Link.where(linkable_id: new_id, linkable_type: obj.linkable_type,
url: obj.url)
unless test
obj.linkable_id = new_id
obj.save!
end
end
restore_multiple("people_languages", Language) do |id, obj|
new_id = @mappings[:people][obj.attachable_id]
test = Language.where(attachable_id: new_id, attachable_type: obj.attachable_type,
code: obj.code)
unless test
obj.attachable_id = new_id
obj.save!
end
end
restore_multiple("people_availabilities", Availability) do |id, obj|
next if obj.nil? or obj.start_date.nil? or obj.end_date.nil?
obj.conference_id = @conference_id
obj.person_id = @mappings[:people][obj.person_id]
obj.day_id = @mappings[:days][obj.day_id]
obj.save!
end
end
def dump_has_many(name, obj, attr)
arr = obj.collect { |t| t.send(attr) }
.flatten.select { |t| not t.nil? }.sort.uniq
dump name, arr
end
def dump(name,obj)
return if obj.nil?
File.open(File.join(@export_dir, name) + '.yaml', 'w') { |f|
if obj.respond_to?("collect")
f.puts obj.collect {|record| record.attributes}.to_yaml
else
f.puts obj.attributes.to_yaml
end
}
return obj
end
def restore(name, obj)
puts "[ ] restore #{name}" if DEBUG
file = File.join(@export_dir, name) + '.yaml'
return unless File.readable? file
records = YAML.load_file(file)
tmp = obj.new(records)
yield records['id'], tmp
end
def restore_multiple(name, obj)
puts "[ ] restore all #{name}" if DEBUG
records = YAML.load_file(File.join(@export_dir, name) + '.yaml')
records.each do |record|
tmp = obj.new(record)
yield record['id'], tmp
end
end
def restore_users(name="users", obj=User)
puts "[ ] restore all #{name}" if DEBUG
records = YAML.load_file(File.join(@export_dir, name) + '.yaml')
records.each do |record|
tmp = obj.new(record)
yield record['id'], record, tmp
end
end
def export_paperclip_files(events,people,attachments)
out_path = File.join(@export_dir, 'attachments.tar.gz')
paths = []
paths << events.select { |e| not e.logo.path.nil? }.collect { |e| e.logo.path.gsub(/^#{Rails.root}\//,'') }
paths << people.select { |e| not e.avatar.path.nil? }.collect { |e| e.avatar.path.gsub(/^#{Rails.root}\//,'') }
paths << attachments.select { |e| not e.attachment.path.nil? }.collect { |e| e.attachment.path.gsub(/^#{Rails.root}\//,'') }
paths.flatten!
# TODO don't use system
system( 'tar', *['-cpz', '-f', out_path, paths].flatten )
end
def import_file(dir, id, file_name)
return if file_name.nil? or file_name.empty?
path = File.join(@export_dir, 'public/system', dir, id.to_s, 'original', file_name)
if (File.readable?(path))
return File.open(path, 'r')
end
return
end
def unpack_paperclip_files()
path = File.join(@export_dir, 'attachments.tar.gz')
system( 'tar', *['-xz', '-f', path, '-C', @export_dir].flatten )
end
def disable_callbacks
EventPerson.skip_callback(:save, :after, :update_speaker_count)
Event.skip_callback(:save, :after, :update_conflicts)
Availability.skip_callback(:save, :after, :update_event_conflicts)
EventRating.skip_callback(:save, :after, :update_average)
EventFeedback.skip_callback(:save, :after, :update_average)
end
def update_counters
ActiveRecord::Base.connection.execute("UPDATE events SET speaker_count=(SELECT count(*) FROM event_people WHERE events.id=event_people.event_id AND event_people.event_role='speaker')")
update_event_average("event_ratings", "average_rating")
update_event_average("event_feedbacks", "average_feedback")
end
def update_event_average(table, field)
ActiveRecord::Base.connection.execute "UPDATE events SET #{field}=(
SELECT sum(rating)/count(rating)
FROM #{table} WHERE events.id = #{table}.event_id)"
end
end
|
class OpenlibertyWebprofile8 < Formula
desc "Lightweight open framework for Java (Jakarta EE Web Profile 8)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/22.0.0.10/openliberty-webProfile8-22.0.0.10.zip"
sha256 "ad50290521282446459d9f104e2989ec321330ef3be23945ab2794159bc323d1"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "b3428d4c3f9a5d265143e71b228a797c5ad2394678e7535ae83822cd6bd9d222"
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-webprofile8").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Jakarta EE Web Profile 8 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-webprofile8", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-webprofile8", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>webProfile-8.0</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
openliberty-webprofile8 22.0.0.11
Closes #114011.
Signed-off-by: Carlo Cabrera <3ffc397d0e4bded29cb84b56167de54c01e3a55b@users.noreply.github.com>
Signed-off-by: BrewTestBot <8a898ee6867e4f2028e63d2a6319b2224641c06c@users.noreply.github.com>
class OpenlibertyWebprofile8 < Formula
desc "Lightweight open framework for Java (Jakarta EE Web Profile 8)"
homepage "https://openliberty.io"
url "https://public.dhe.ibm.com/ibmdl/export/pub/software/openliberty/runtime/release/22.0.0.11/openliberty-webProfile8-22.0.0.11.zip"
sha256 "002361aef8b92e3768b487aa10157c206d78f33db39af285e548aa9a30fae007"
license "EPL-1.0"
livecheck do
url "https://openliberty.io/api/builds/data"
regex(/openliberty[._-]v?(\d+(?:\.\d+)+)\.zip/i)
end
bottle do
sha256 cellar: :any_skip_relocation, all: "b3428d4c3f9a5d265143e71b228a797c5ad2394678e7535ae83822cd6bd9d222"
end
depends_on "openjdk"
def install
rm_rf Dir["bin/**/*.bat"]
prefix.install_metafiles
libexec.install Dir["*"]
(bin/"openliberty-webprofile8").write_env_script "#{libexec}/bin/server",
Language::Java.overridable_java_home_env
end
def caveats
<<~EOS
The home of Open Liberty Jakarta EE Web Profile 8 is:
#{opt_libexec}
EOS
end
test do
ENV["WLP_USER_DIR"] = testpath
begin
system bin/"openliberty-webprofile8", "start"
assert_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
ensure
system bin/"openliberty-webprofile8", "stop"
end
refute_predicate testpath/"servers/.pid/defaultServer.pid", :exist?
assert_match "<feature>webProfile-8.0</feature>", (testpath/"servers/defaultServer/server.xml").read
end
end
|
class ZshSyntaxHighlighting < Formula
desc "Fish shell like syntax highlighting for zsh"
homepage "https://github.com/zsh-users/zsh-syntax-highlighting"
url "https://github.com/zsh-users/zsh-syntax-highlighting.git",
tag: "0.7.1",
revision: "932e29a0c75411cb618f02995b66c0a4a25699bc"
license "BSD-3-Clause"
head "https://github.com/zsh-users/zsh-syntax-highlighting.git"
bottle do
cellar :any_skip_relocation
sha256 "6b7d4cdc41b56c842a4b76f9901d922d1f39bd638e94249881078a873de8970b" => :catalina
sha256 "6b7d4cdc41b56c842a4b76f9901d922d1f39bd638e94249881078a873de8970b" => :mojave
sha256 "6b7d4cdc41b56c842a4b76f9901d922d1f39bd638e94249881078a873de8970b" => :high_sierra
end
uses_from_macos "zsh" => [:build, :test]
def install
system "make", "install", "PREFIX=#{prefix}"
end
def caveats
<<~EOS
To activate the syntax highlighting, add the following at the end of your .zshrc:
source #{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
If you receive "highlighters directory not found" error message,
you may need to add the following to your .zshenv:
export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=#{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/highlighters
EOS
end
test do
assert_match "#{version}\n",
shell_output("zsh -c '. #{pkgshare}/zsh-syntax-highlighting.zsh && echo $ZSH_HIGHLIGHT_VERSION'")
end
end
zsh-syntax-highlighting: update 0.7.1 bottle.
class ZshSyntaxHighlighting < Formula
desc "Fish shell like syntax highlighting for zsh"
homepage "https://github.com/zsh-users/zsh-syntax-highlighting"
url "https://github.com/zsh-users/zsh-syntax-highlighting.git",
tag: "0.7.1",
revision: "932e29a0c75411cb618f02995b66c0a4a25699bc"
license "BSD-3-Clause"
head "https://github.com/zsh-users/zsh-syntax-highlighting.git"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "8b240a93c28b0c190c427afee55b80a0195dc0ed0cdb2ec956871330e0b2f3a5" => :catalina
sha256 "ab57b09a3770c0497b1704ca86bbd285d9bcab439316c0bd7f72ab72e8597d92" => :mojave
sha256 "f8e941c6208a3b895a174be341a9ef2c114a3d5efeb0e86b421825b2aee0b943" => :high_sierra
end
uses_from_macos "zsh" => [:build, :test]
def install
system "make", "install", "PREFIX=#{prefix}"
end
def caveats
<<~EOS
To activate the syntax highlighting, add the following at the end of your .zshrc:
source #{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
If you receive "highlighters directory not found" error message,
you may need to add the following to your .zshenv:
export ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR=#{HOMEBREW_PREFIX}/share/zsh-syntax-highlighting/highlighters
EOS
end
test do
assert_match "#{version}\n",
shell_output("zsh -c '. #{pkgshare}/zsh-syntax-highlighting.zsh && echo $ZSH_HIGHLIGHT_VERSION'")
end
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: tarvit-helpers 0.0.4 ruby lib
Gem::Specification.new do |s|
s.name = "tarvit-helpers"
s.version = "0.0.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Vitaly Tarasenko"]
s.date = "2015-06-17"
s.description = " Simple extensions to standard Ruby classes and useful helpers. "
s.email = "vetal.tarasenko@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"lib/modules/non_shared_accessors.rb",
"lib/modules/simple_crypt.rb",
"lib/tarvit-helpers.rb",
"spec/modules/non_shared_accessors_spec.rb",
"spec/modules/simple_crypt_spec.rb",
"spec/spec_helper.rb",
"tarvit-helpers.gemspec"
]
s.homepage = "http://github.com/tarvit/tarvit-helpers"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "Simple extensions to standard Ruby classes and useful helpers."
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_development_dependency(%q<simplecov>, [">= 0"])
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
else
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
end
Regenerate gemspec for version 0.0.5
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: tarvit-helpers 0.0.5 ruby lib
Gem::Specification.new do |s|
s.name = "tarvit-helpers"
s.version = "0.0.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Vitaly Tarasenko"]
s.date = "2015-06-19"
s.description = " Simple extensions to standard Ruby classes and useful helpers. "
s.email = "vetal.tarasenko@gmail.com"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.md"
]
s.files = [
".document",
"Gemfile",
"LICENSE.txt",
"README.md",
"Rakefile",
"VERSION",
"lib/modules/non_shared_accessors.rb",
"lib/modules/simple_crypt.rb",
"lib/tarvit-helpers.rb",
"spec/modules/non_shared_accessors_spec.rb",
"spec/modules/simple_crypt_spec.rb",
"spec/spec_helper.rb",
"tarvit-helpers.gemspec"
]
s.homepage = "http://github.com/tarvit/tarvit-helpers"
s.licenses = ["MIT"]
s.rubygems_version = "2.2.2"
s.summary = "Simple extensions to standard Ruby classes and useful helpers."
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<activesupport>, ["~> 4.2"])
s.add_development_dependency(%q<shoulda>, [">= 0"])
s.add_development_dependency(%q<rdoc>, ["~> 3.12"])
s.add_development_dependency(%q<bundler>, ["~> 1.0"])
s.add_development_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_development_dependency(%q<simplecov>, [">= 0"])
else
s.add_dependency(%q<activesupport>, ["~> 4.2"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
else
s.add_dependency(%q<activesupport>, ["~> 4.2"])
s.add_dependency(%q<shoulda>, [">= 0"])
s.add_dependency(%q<rdoc>, ["~> 3.12"])
s.add_dependency(%q<bundler>, ["~> 1.0"])
s.add_dependency(%q<jeweler>, ["~> 2.0.1"])
s.add_dependency(%q<simplecov>, [">= 0"])
end
end
|
require 'minitest/autorun'
require_relative '../lib/eavi/visitor'
require_relative 'fixtures'
include Eavi::Fixtures
class VisitorTest < MiniTest::Test
def setup
@page = Page.new
@reader = Reader.new
Reader.reset_visit_methods
Printer.reset_visit_methods
end
def test_visit__when_included
@reader.class.when_visiting Page do
return 'Reading'
end
assert_equal @reader.visit(@page),
'Reading'
assert_equal @reader.visit(@page, as: Page),
'Reading'
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit(@page, as: String)
end
assert_raises TypeError do
@reader.visit('string')
end
assert_raises TypeError do
@reader.visit('string', as: String)
end
assert_raises TypeError do
@reader.visit(@page, as: String)
end
@reader.class.when_visiting Page do
return self
end
assert_same @reader.visit(@page),
@reader
end
def test_visit__when_extended
Printer.when_visiting Page do
return 'Printing'
end
assert_equal Printer.visit(@page),
'Printing'
assert_equal Printer.visit(@page, as: Page),
'Printing'
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page, as: String)
end
assert_raises TypeError do
Printer.visit('string')
end
assert_raises TypeError do
Printer.visit('string', as: String)
end
assert_raises TypeError do
Printer.visit(@page, as: String)
end
Printer.when_visiting Page do
return self
end
assert_same Printer.visit(@page),
Printer
end
def test_visit__with_args
Printer.when_visiting String do |_, *args|
return args
end
assert_equal Printer.visit('something', 1, 2),
[1, 2]
Printer.when_visiting String do |_, a, b|
return { a: a, b: b }
end
assert_equal Printer.visit('something', 1, 2),
{ a: 1, b: 2 }
end
def test_visit__with_inheritance
Reader.when_visiting Page do
return 'Reading'
end
new_reader = NewReader.new
assert_equal new_reader.visit(@page),
'Reading'
Printer.when_visiting Page do
return 'Printing'
end
assert_equal NewPrinter.visit(@page),
'Printing'
end
def test_alias_visit_method
Printer.when_visiting Page do
# [...]
end
Printer.send(:alias_visit_method, :print)
assert_respond_to Printer, :print, @page
Reader.when_visiting Page do
# [...]
end
Reader.send(:alias_visit_method, :read)
assert_respond_to @reader, :read, @page
end
def test_add_visit_methods
Printer.when_visiting Array do
return 'Visiting an array'
end
assert_equal Printer.visit([]),
'Visiting an array'
end
def test_remove_visit_methods
Printer.when_visiting Page do
'Printing'
end
Printer.remove_visit_method(Page)
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page)
end
end
def test_reset_visit_methods
Printer.when_visiting Page do
'Printing'
end
refute_empty Printer.visit_methods
Printer.reset_visit_methods
assert_empty Printer.visit_methods
end
def test_visit_methods
Printer.when_visiting String, Array, Hash do
# [...]
end
Printer.visit_methods.each do |method|
assert_respond_to Printer, method
end
end
def test_visitable_types
Printer.when_visiting String, Array, Hash do
# [...]
end
assert_equal Printer.visitable_types,
[String, Array, Hash]
end
end
More test for the Visitor#visit (about the first argument)
require 'minitest/autorun'
require_relative '../lib/eavi/visitor'
require_relative 'fixtures'
include Eavi::Fixtures
class VisitorTest < MiniTest::Test
def setup
@page = Page.new
@reader = Reader.new
Reader.reset_visit_methods
Printer.reset_visit_methods
end
def test_visit__when_included
@reader.class.when_visiting Page do
return 'Reading'
end
assert_equal @reader.visit(@page),
'Reading'
assert_equal @reader.visit(@page, as: Page),
'Reading'
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit(@page, as: String)
end
assert_raises TypeError do
@reader.visit('string')
end
assert_raises TypeError do
@reader.visit('string', as: String)
end
assert_raises TypeError do
@reader.visit(@page, as: String)
end
@reader.class.when_visiting Page do
return self
end
assert_same @reader.visit(@page),
@reader
@reader.when_visiting Page do |page|
return page
end
assert_same @reader.visit(@page),
@page
end
def test_visit__when_extended
Printer.when_visiting Page do
return 'Printing'
end
assert_equal Printer.visit(@page),
'Printing'
assert_equal Printer.visit(@page, as: Page),
'Printing'
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page, as: String)
end
assert_raises TypeError do
Printer.visit('string')
end
assert_raises TypeError do
Printer.visit('string', as: String)
end
assert_raises TypeError do
Printer.visit(@page, as: String)
end
Printer.when_visiting Page do
return self
end
assert_same Printer.visit(@page),
Printer
Printer.when_visiting Page do |page|
return page
end
assert_same Printer.visit(@page),
@page
end
def test_visit__with_args
Printer.when_visiting String do |_, *args|
return args
end
assert_equal Printer.visit('something', 1, 2),
[1, 2]
Printer.when_visiting String do |_, a, b|
return { a: a, b: b }
end
assert_equal Printer.visit('something', 1, 2),
{ a: 1, b: 2 }
end
def test_visit__with_inheritance
Reader.when_visiting Page do
return 'Reading'
end
new_reader = NewReader.new
assert_equal new_reader.visit(@page),
'Reading'
Printer.when_visiting Page do
return 'Printing'
end
assert_equal NewPrinter.visit(@page),
'Printing'
end
def test_alias_visit_method
Printer.when_visiting Page do
# [...]
end
Printer.send(:alias_visit_method, :print)
assert_respond_to Printer, :print, @page
Reader.when_visiting Page do
# [...]
end
Reader.send(:alias_visit_method, :read)
assert_respond_to @reader, :read, @page
end
def test_add_visit_methods
Printer.when_visiting Array do
return 'Visiting an array'
end
assert_equal Printer.visit([]),
'Visiting an array'
end
def test_remove_visit_methods
Printer.when_visiting Page do
'Printing'
end
Printer.remove_visit_method(Page)
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page)
end
end
def test_reset_visit_methods
Printer.when_visiting Page do
'Printing'
end
refute_empty Printer.visit_methods
Printer.reset_visit_methods
assert_empty Printer.visit_methods
end
def test_visit_methods
Printer.when_visiting String, Array, Hash do
# [...]
end
Printer.visit_methods.each do |method|
assert_respond_to Printer, method
end
end
def test_visitable_types
Printer.when_visiting String, Array, Hash do
# [...]
end
assert_equal Printer.visitable_types,
[String, Array, Hash]
end
end
|
require 'minitest/autorun'
require_relative '../lib/eavi/visitor'
require_relative 'fixtures'
include Eavi::Fixtures
class VisitorTest < MiniTest::Test
def setup
@page = Page.new
@reader = Reader.new
Reader.reset_visit_methods
Printer.reset_visit_methods
end
def test_visit__when_included
@reader.class.when_visiting Page do
return 'Reading'
end
assert_equal @reader.visit(@page),
'Reading'
assert_equal @reader.visit(@page, as: Page),
'Reading'
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit(@page, as: String)
end
assert_raises TypeError do
@reader.visit('string')
end
assert_raises TypeError do
@reader.visit('string', as: String)
end
assert_raises TypeError do
@reader.visit(@page, as: String)
end
@reader.class.when_visiting Page do |page|
return self
end
assert_same @reader.visit(@page),
@reader
end
def test_visit__when_extended
Printer.when_visiting Page do |page|
return 'Printing'
end
assert_equal Printer.visit(@page),
'Printing'
assert_equal Printer.visit(@page, as: Page),
'Printing'
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page, as: String)
end
assert_raises TypeError do
Printer.visit('string')
end
assert_raises TypeError do
Printer.visit('string', as: String)
end
assert_raises TypeError do
Printer.visit(@page, as: String)
end
Printer.when_visiting Page do |page|
return self
end
assert_same Printer.visit(@page),
Printer
end
def test_visit__with_args
Printer.when_visiting String do |string, *args|
return args
end
assert_equal Printer.visit('something', 1, 2),
[1, 2]
Printer.when_visiting String do |string, a, b|
return { a: a, b: b }
end
assert_equal (Printer.visit 'something', 1, 2),
{ a: 1, b: 2 }
end
def test_visit__with_inheritance
Reader.when_visiting Page do |page|
return 'Reading'
end
new_reader = NewReader.new
assert_equal new_reader.visit(@page),
'Reading'
Printer.when_visiting Page do |page|
return 'Printing'
end
assert_equal NewPrinter.visit(@page),
'Printing'
end
def test_alias_visit_method
Printer.when_visiting Page do
# [...]
end
Printer.send(:alias_visit_method, :print)
assert_respond_to Printer, :print, @page
Reader.when_visiting Page do
# [...]
end
Reader.send(:alias_visit_method, :read)
assert_respond_to @reader, :read, @page
end
def test_add_visit_methods
Printer.when_visiting Array do |array|
return 'Visiting an array'
end
assert_equal Printer.visit([]),
'Visiting an array'
end
def test_remove_visit_methods
Printer.when_visiting Page do |page|
'Printing'
end
Printer.remove_visit_method(Page)
assert_raises Eavi::NoVisitMethodError do |page|
Printer.visit(@page)
end
end
def test_reset_visit_methods
Printer.when_visiting Page do
'Printing'
end
refute_empty Printer.visit_methods
Printer.reset_visit_methods
assert_empty Printer.visit_methods
end
def test_visit_methods
Printer.when_visiting String, Array, Hash do
# [...]
end
Printer.visit_methods.each do |method|
assert_respond_to Printer, method
end
end
def test_visitable_types
Printer.when_visiting String, Array, Hash do
# [...]
end
assert_equal Printer.visitable_types,
[String, Array, Hash]
end
end
Code style changes in the test file
require 'minitest/autorun'
require_relative '../lib/eavi/visitor'
require_relative 'fixtures'
include Eavi::Fixtures
class VisitorTest < MiniTest::Test
def setup
@page = Page.new
@reader = Reader.new
Reader.reset_visit_methods
Printer.reset_visit_methods
end
def test_visit__when_included
@reader.class.when_visiting Page do
return 'Reading'
end
assert_equal @reader.visit(@page),
'Reading'
assert_equal @reader.visit(@page, as: Page),
'Reading'
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
@reader.visit(@page, as: String)
end
assert_raises TypeError do
@reader.visit('string')
end
assert_raises TypeError do
@reader.visit('string', as: String)
end
assert_raises TypeError do
@reader.visit(@page, as: String)
end
@reader.class.when_visiting Page do
return self
end
assert_same @reader.visit(@page),
@reader
end
def test_visit__when_extended
Printer.when_visiting Page do
return 'Printing'
end
assert_equal Printer.visit(@page),
'Printing'
assert_equal Printer.visit(@page, as: Page),
'Printing'
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string')
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit('string', as: String)
end
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page, as: String)
end
assert_raises TypeError do
Printer.visit('string')
end
assert_raises TypeError do
Printer.visit('string', as: String)
end
assert_raises TypeError do
Printer.visit(@page, as: String)
end
Printer.when_visiting Page do
return self
end
assert_same Printer.visit(@page),
Printer
end
def test_visit__with_args
Printer.when_visiting String do |_, *args|
return args
end
assert_equal Printer.visit('something', 1, 2),
[1, 2]
Printer.when_visiting String do |_, a, b|
return { a: a, b: b }
end
assert_equal Printer.visit('something', 1, 2),
{ a: 1, b: 2 }
end
def test_visit__with_inheritance
Reader.when_visiting Page do
return 'Reading'
end
new_reader = NewReader.new
assert_equal new_reader.visit(@page),
'Reading'
Printer.when_visiting Page do
return 'Printing'
end
assert_equal NewPrinter.visit(@page),
'Printing'
end
def test_alias_visit_method
Printer.when_visiting Page do
# [...]
end
Printer.send(:alias_visit_method, :print)
assert_respond_to Printer, :print, @page
Reader.when_visiting Page do
# [...]
end
Reader.send(:alias_visit_method, :read)
assert_respond_to @reader, :read, @page
end
def test_add_visit_methods
Printer.when_visiting Array do
return 'Visiting an array'
end
assert_equal Printer.visit([]),
'Visiting an array'
end
def test_remove_visit_methods
Printer.when_visiting Page do
'Printing'
end
Printer.remove_visit_method(Page)
assert_raises Eavi::NoVisitMethodError do
Printer.visit(@page)
end
end
def test_reset_visit_methods
Printer.when_visiting Page do
'Printing'
end
refute_empty Printer.visit_methods
Printer.reset_visit_methods
assert_empty Printer.visit_methods
end
def test_visit_methods
Printer.when_visiting String, Array, Hash do
# [...]
end
Printer.visit_methods.each do |method|
assert_respond_to Printer, method
end
end
def test_visitable_types
Printer.when_visiting String, Array, Hash do
# [...]
end
assert_equal Printer.visitable_types,
[String, Array, Hash]
end
end
|
# encoding: utf-8
require 'iso/iban/backports'
require 'iso/iban/invalid'
require 'iso/iban/specification'
require 'iso/iban/version'
require 'yaml'
module ISO
# IBAN - ISO 13616-1
#
# General IBAN Information
# ========================
#
# * What is an IBAN?
# IBAN stands for International Bank Account Number. It is the ISO 13616
# international standard for numbering bank accounts. In 2006, the
# International Organization for Standardization (ISO) designated SWIFT as
# the Registration Authority for ISO 13616.
#
# * Use
# The IBAN facilitates the communication and processing of cross-border
# transactions. It allows exchanging account identification details in a
# machine-readable form.
#
#
# The ISO 13616 IBAN Standard
# ===========================
#
# * Structure
# The IBAN structure is defined in ISO 13616-1 and consists of a two-letter
# ISO 3166-1 country code, followed by two check digits and up to thirty
# alphanumeric characters for a BBAN (Basic Bank Account Number) which has a
# fixed length per country and, included within it, a bank identifier with a
# fixed position and a fixed length per country. The check digits are
# calculated based on the scheme defined in ISO/IEC 7064 (MOD97-10).
#
# * Terms and definitions
# Bank identifier: The identifier that uniquely identifies the financial
# institution and, when appropriate, the branch of that financial institution
# servicing an account
#
# `In this registry, the branch identifier format is shown specifically, when
# present.`
#
# *BBAN*: basic bank account number: The identifier that uniquely identifies
# an individual account, at a specific financial institution, in a particular
# country. The BBAN includes a bank identifier of the financial institution
# servicing that account.
# *IBAN*: international bank account number: The expanded version of the
# basic bank account number (BBAN), intended for use internationally. The
# IBAN uniquely identifies an individual account, at a specific financial
# institution, in a particular country.
#
# * Submitters
# Nationally-agreed, ISO13616-compliant IBAN formats are submitted to the
# registration authority exclusively by the National Standards Body or the
# National Central Bank of the country.
class IBAN
include Comparable
# Character code translation used to convert an IBAN into its numeric
# (digits-only) form
CharacterCodes = Hash[('0'..'9').zip('0'..'9')+('a'..'z').zip(10..35)+('A'..'Z').zip(10..35)]
# All uppercase letters
UpperAlpha = [*'A'..'Z']
# All lowercase letters
LowerAlpha = [*'a'..'z']
# All digits
Digits = [*'0'..'9']
# All uppercase letters, lowercase letters and digits
AlphaNumeric = [*'A'..'Z', *'a'..'z', *'0'..'9']
# All specifications, see ISO::IBAN::Specification
@specifications = nil
# @note
# Using `require 'iso/iban'` will automatically invoke this method.
# If you do not wish this behavior, `require 'iso/iban/no_autoload'` instead.
#
# Load the IBAN specifications file, which determines how the IBAN
# for any given country looks like.
#
# It will use the following sources in this order (first one which exists wins)
#
# * Path passed as spec_file parameter
# * Path provided by the env variable IBAN_SPECIFICATIONS
# * The file ../data/iso-iban/specs.yaml relative to the lib dir
# * The Gem datadir path
#
# @param [String] spec_file
# Override the default specifications file path.
#
# @return [self]
def self.load_specifications(spec_file=nil)
if spec_file then
# do nothing
elsif ENV['IBAN_SPECIFICATIONS'] then
spec_file = ENV['IBAN_SPECIFICATIONS']
else
spec_file = File.expand_path('../../../../data/iso-iban/specs.yaml', __FILE__)
if !File.file?(spec_file) && defined?(Gem) && Gem.datadir('iso-iban')
spec_file = Gem.datadir('iso-iban')+'/specs.yaml'
end
end
if spec_file && File.file?(spec_file)
@specifications = ISO::IBAN::Specification.load_yaml(spec_file)
elsif spec_file
raise "Could not load IBAN specifications, specs file #{spec_file.inspect} does not exist or can't be read."
else
raise "Could not load IBAN specifications, no specs file found."
end
self
end
# @return [Hash<String => ISO::IBAN::Specification>]
# A hash with the country (ISO3166 2-letter) as key and the specification for that country as value
def self.specifications
@specifications || raise("No specifications have been loaded yet - Check the docs for ISO::IBAN::load_specifications.")
end
# @param [String] a2_country_code
# The country (ISO3166 2-letter), e.g. 'CH' or 'DE'.
#
# @return [ISO::IBAN::Specification]
# The specification for the given country
def self.specification(a2_country_code, *default, &default_block)
specifications.fetch(a2_country_code, *default, &default_block)
end
# @param [String] iban
# An IBAN number, either in compact or human format.
#
# @return [true, false]
# Whether the IBAN is valid.
# See {#validate} for details.
def self.valid?(iban)
parse(iban).valid?
end
# @param [String] iban
# An IBAN number, either in compact or human format.
#
# @return [Array<Symbol>]
# An array with a code of all validation errors, empty if valid.
# See {#validate} for details.
def self.validate(iban)
parse(iban).validate
end
# @param [String] iban
# The IBAN in either compact or human readable form.
#
# @return [String]
# The IBAN in compact form, all whitespace stripped.
def self.strip(iban)
iban.delete("\n\r\t -")
end
# Like ISO::IBAN.parse, but raises a ISO::IBAN::Invalid exception if the IBAN is invalid.
#
# @param [String] iban
# The IBAN in either compact or human readable form.
#
# @return [ISO::IBAN]
# An IBAN instance representing the passed IBAN number.
def self.parse!(iban_number)
iban = parse(iban_number)
raise Invalid.new(iban) unless iban.valid?
iban
end
# @param [String] iban
# The IBAN in either compact or human readable form.
#
# @return [ISO::IBAN]
# An IBAN instance representing the passed IBAN number.
def self.parse(iban_number)
new(strip(iban_number))
end
# Generate an IBAN from country code and components, automatically filling in the checksum.
#
# @example Generate an IBAN for UBS Switzerland with account number '12345'
# ISO::IBAN.generate('CH', '216', '12345') # => #<ISO::IBAN CH92 0021 6000 0000 1234 5>
#
# @param [String] country
# The ISO-3166 2-letter country code.
#
def self.generate(country, *components)
spec = specification(country)
justified = spec.component_lengths.zip(components).map { |length, component| component.rjust(length, "0") }
iban = new(country+'??'+justified.join(''))
iban.update_checksum!
iban
end
# @param [String] countries
# A list of 2 letter country codes. If empty, all countries in
# ISO::IBAN::specifications are used.
#
# @return [ISO::IBAN] A random, valid IBAN
def self.random(*countries)
countries = specifications.keys if countries.empty?
country = countries.sample
account = specification(country).iban_structure.scan(/([A-Z]+)|(\d+)(!?)([nac])/).map { |exact, length, fixed, code|
if exact
exact
elsif code == 'a'
Array.new(length.to_i) { UpperAlpha.sample }.join('')
elsif code == 'c'
Array.new(length.to_i) { AlphaNumeric.sample }.join('')
elsif code == 'e'
' '*length.to_i
elsif code == 'n'
Array.new(length.to_i) { Digits.sample }.join('')
end
}.join('')
account[2,2] = '??'
iban = new(account)
iban.update_checksum!
iban
end
# Converts a String into its digits-only form, i.e. all characters a-z are replaced with their corresponding
# digit sequences, according to the IBAN specification.
#
# @param [String] string
# The string to convert into its numeric form.
#
# @return [String] The string in its numeric, digits-only form.
def self.numerify(string)
string.downcase.gsub(/\D/) { |char|
CharacterCodes.fetch(char) {
raise ArgumentError, "The string contains an invalid character #{char.inspect}"
}
}.to_i
end
# @return [String] The standard form of the IBAN for machine communication, without spaces.
attr_reader :compact
# @return [String] The ISO-3166 2-letter country code.
attr_reader :country
# @return [ISO::IBAN::Specification] The specification for this IBAN (determined by its country).
attr_reader :specification
# @param [String] iban
# The IBAN number, must be in compact form. Use ISO::IBAN::parse for formatted IBANs.
def initialize(iban)
raise ArgumentError, "String expected for iban, but got #{iban.class}" unless iban.is_a?(String)
@compact = iban.b
@country = iban[0,2]
@specification = self.class.specification(@country, nil)
end
# @example Formatted IBAN
#
# ISO::IBAN.new('CH')
#
# @return [String] The IBAN in its formatted form, which is more human readable than the compact form.
def formatted
@_formatted ||= @compact.gsub(/.{4}(?=.)/, '\0 ')
end
# @return [String]
# IBAN in its numeric form, i.e. all characters a-z are replaced with their corresponding
# digit sequences.
def numeric
@compact.size < 5 ? nil : self.class.numerify(@compact[4..-1]+@compact[0,4])
end
# @return [true, false]
# Whether the IBAN is valid.
# See {#validate} for details.
def valid?
valid_country? && valid_checksum? && valid_length? && valid_format?
end
# Validation error codes:
#
# * :invalid_country
# * :invalid_checksum
# * :invalid_length
# * :invalid_format
#
# Invalid country means the country is unknown (char 1 & 2 in the IBAN).
# Invalid checksum means the two check digits (char 3 & 4 in the IBAN).
# Invalid length means the IBAN does not comply with the length specified for the country of that IBAN.
# Invalid format means the IBAN does not comply with the format specified for the country of that IBAN.
#
# @return [Array<Symbol>] An array with a code of all validation errors, empty if valid.
def validate
errors = []
errors << :invalid_characters unless valid_characters?
errors << :invalid_country unless valid_country?
errors << :invalid_checksum unless valid_characters? && valid_checksum?
errors << :invalid_length unless valid_length?
errors << :invalid_format unless valid_format?
errors
end
# @return [String] The checksum digits in the IBAN.
def checksum_digits
@compact[2,2]
end
# @return [String] The BBAN of the IBAN.
def bban
@compact[4..-1]
end
# @return [String, nil] The bank code part of the IBAN, nil if not applicable.
def bank_code
if @specification && @specification.bank_position_from && @specification.bank_position_to
@compact[@specification.bank_position_from..@specification.bank_position_to]
else
nil
end
end
# @return [String, nil] The branch code part of the IBAN, nil if not applicable.
def branch_code
if @specification && @specification.branch_position_from && @specification.branch_position_to
@compact[@specification.branch_position_from..@specification.branch_position_to]
else
nil
end
end
# @return [String] The account code part of the IBAN.
def account_code
@compact[((@specification.branch_position_to || @specification.bank_position_to || 3)+1)..-1]
end
# @example
# invalid = "hägar"
# invalid.encoding # => #<Encoding:UTF-8>
# ISO::IBAN.new(invalid).invalid_characters # => ["\xC3", "\xA4"]
# ISO::IBAN.new(invalid).invalid_characters('utf-8') # => ["ä"]
#
# @param [String, Encoding, nil] input_encoding
# ISO::IBAN::new interprets the passed IBAN as binary.
# If you got the IBAN from a source which is not binary, you should provide that encoding.
# Otherwise an invalid character may be split into multiple bytes.
#
# @return [Array] An Array with all invalid characters.
def invalid_characters(input_encoding=nil)
iban = input_encoding ? @compact.dup.force_encoding(input_encoding) : @compact
iban.gsub(/[A-Z0-9?]*/i, '').chars.uniq
end
def valid_characters?
@compact =~ /\A[A-Z]{2}(?:\d\d|\?\?)[A-Z0-9]*\z/in ? true : false
end
# @return [true, false] Whether the country of the IBAN is valid.
def valid_country?
@specification ? true : false
end
# @return [true, false] Whether the format of the IBAN is valid.
def valid_format?
@specification && @specification.iban_regex =~ @compact ? true : false
end
# @return [true, false] Whether the length of the IBAN is valid.
def valid_length?
@specification && @compact.size == @specification.iban_length ? true : false
end
# @return [true, false] Whether the checksum of the IBAN is valid.
def valid_checksum?
numerified = numeric()
numerified && (numerified % 97 == 1)
end
# See Object#<=>
#
# @return [-1, 0, 1, nil]
def <=>(other)
other.respond_to?(:compact) ? @compact <=> other.compact : nil
end
# Requires that the checksum digits were left as '??', replaces them with
# the proper checksum.
#
# @return [self]
def update_checksum!
raise "Checksum digit placeholders missing" unless @compact[2,2] == '??'
@compact[2,2] = calculated_check_digits
self
end
# @return [String] The check-digits as calculated from the IBAN.
def calculated_check_digits
"%02d" % (98-(self.class.numerify(bban+@country)*100)%97)
end
# @return [true, false]
# Whether two ISO::IBANs are equal.
# Comparison is based on class and IBAN number
def eql?(other)
self.class.equal?(other.class) && self == other
end
# @return [Integer]
# A hash value, see Object#hash
def hash
[self.class, @compact].hash
end
# See Object#inspect
def inspect
sprintf "#<%p %s>", self.class, formatted
end
# @return [String] The compact form of the IBAN as a String.
def to_s
@compact.dup
end
# @return [Array]
# The individual IBAN components as defined by the SWIFT specification.
# An empty array if this IBAN does not have a specification.
def to_a
@_components ||= @specification ? @compact.match(@specification.iban_regex).captures : []
@_components.dup
end
end
end
Improved documentation.
# encoding: utf-8
require 'iso/iban/backports'
require 'iso/iban/invalid'
require 'iso/iban/specification'
require 'iso/iban/version'
require 'yaml'
module ISO
# IBAN - ISO 13616-1
#
# General IBAN Information
# ========================
#
# * What is an IBAN?
# IBAN stands for International Bank Account Number. It is the ISO 13616
# international standard for numbering bank accounts. In 2006, the
# International Organization for Standardization (ISO) designated SWIFT as
# the Registration Authority for ISO 13616.
#
# * Use
# The IBAN facilitates the communication and processing of cross-border
# transactions. It allows exchanging account identification details in a
# machine-readable form.
#
#
# The ISO 13616 IBAN Standard
# ===========================
#
# * Structure
# The IBAN structure is defined in ISO 13616-1 and consists of a two-letter
# ISO 3166-1 country code, followed by two check digits and up to thirty
# alphanumeric characters for a BBAN (Basic Bank Account Number) which has a
# fixed length per country and, included within it, a bank identifier with a
# fixed position and a fixed length per country. The check digits are
# calculated based on the scheme defined in ISO/IEC 7064 (MOD97-10).
#
# * Terms and definitions
# Bank identifier: The identifier that uniquely identifies the financial
# institution and, when appropriate, the branch of that financial institution
# servicing an account
#
# `In this registry, the branch identifier format is shown specifically, when
# present.`
#
# *BBAN*: basic bank account number: The identifier that uniquely identifies
# an individual account, at a specific financial institution, in a particular
# country. The BBAN includes a bank identifier of the financial institution
# servicing that account.
# *IBAN*: international bank account number: The expanded version of the
# basic bank account number (BBAN), intended for use internationally. The
# IBAN uniquely identifies an individual account, at a specific financial
# institution, in a particular country.
#
# * Submitters
# Nationally-agreed, ISO13616-compliant IBAN formats are submitted to the
# registration authority exclusively by the National Standards Body or the
# National Central Bank of the country.
class IBAN
include Comparable
# Character code translation used to convert an IBAN into its numeric
# (digits-only) form
CharacterCodes = Hash[('0'..'9').zip('0'..'9')+('a'..'z').zip(10..35)+('A'..'Z').zip(10..35)]
# All uppercase letters
UpperAlpha = [*'A'..'Z']
# All lowercase letters
LowerAlpha = [*'a'..'z']
# All digits
Digits = [*'0'..'9']
# All uppercase letters, lowercase letters and digits
AlphaNumeric = [*'A'..'Z', *'a'..'z', *'0'..'9']
# All specifications, see ISO::IBAN::Specification
@specifications = nil
# @note
# Using `require 'iso/iban'` will automatically invoke this method.
# If you do not wish this behavior, `require 'iso/iban/no_autoload'` instead.
#
# Load the IBAN specifications file, which determines how the IBAN
# for any given country looks like.
#
# It will use the following sources in this order (first one which exists wins)
#
# * Path passed as spec_file parameter
# * Path provided by the env variable IBAN_SPECIFICATIONS
# * The file ../data/iso-iban/specs.yaml relative to the lib dir
# * The Gem datadir path
#
# @param [String] spec_file
# Override the default specifications file path.
#
# @return [self]
def self.load_specifications(spec_file=nil)
if spec_file then
# do nothing
elsif ENV['IBAN_SPECIFICATIONS'] then
spec_file = ENV['IBAN_SPECIFICATIONS']
else
spec_file = File.expand_path('../../../../data/iso-iban/specs.yaml', __FILE__)
if !File.file?(spec_file) && defined?(Gem) && Gem.datadir('iso-iban')
spec_file = Gem.datadir('iso-iban')+'/specs.yaml'
end
end
if spec_file && File.file?(spec_file)
@specifications = ISO::IBAN::Specification.load_yaml(spec_file)
elsif spec_file
raise "Could not load IBAN specifications, specs file #{spec_file.inspect} does not exist or can't be read."
else
raise "Could not load IBAN specifications, no specs file found."
end
self
end
# @return [Hash<String => ISO::IBAN::Specification>]
# A hash with the country (ISO3166 2-letter) as key and the specification for that country as value
def self.specifications
@specifications || raise("No specifications have been loaded yet - Check the docs for ISO::IBAN::load_specifications.")
end
# @param [String] a2_country_code
# The country (ISO3166 2-letter), e.g. 'CH' or 'DE'.
#
# @return [ISO::IBAN::Specification]
# The specification for the given country
def self.specification(a2_country_code, *default, &default_block)
specifications.fetch(a2_country_code, *default, &default_block)
end
# @param [String] iban
# An IBAN number, either in compact or human format.
#
# @return [true, false]
# Whether the IBAN is valid.
# See {#validate} for details.
def self.valid?(iban)
parse(iban).valid?
end
# @param [String] iban
# An IBAN number, either in compact or human format.
#
# @return [Array<Symbol>]
# An array with a code of all validation errors, empty if valid.
# See {#validate} for details.
def self.validate(iban)
parse(iban).validate
end
# @param [String] iban
# The IBAN in either compact or human readable form.
#
# @return [String]
# The IBAN in compact form, all whitespace and dashes stripped.
def self.strip(iban)
iban.delete("\n\r\t -")
end
# Like ISO::IBAN.parse, but raises a ISO::IBAN::Invalid exception if the IBAN is invalid.
#
# @param [String] iban
# The IBAN in either compact or human readable form.
#
# @return [ISO::IBAN]
# An IBAN instance representing the passed IBAN number.
def self.parse!(iban_number)
iban = parse(iban_number)
raise Invalid.new(iban) unless iban.valid?
iban
end
# @param [String] iban
# The IBAN in either compact or human readable form.
#
# @return [ISO::IBAN]
# An IBAN instance representing the passed IBAN number.
def self.parse(iban_number)
new(strip(iban_number))
end
# Generate an IBAN from country code and components, automatically filling in the checksum.
#
# @example Generate an IBAN for UBS Switzerland with account number '12345'
# ISO::IBAN.generate('CH', '216', '12345') # => #<ISO::IBAN CH92 0021 6000 0000 1234 5>
#
# @param [String] country
# The ISO-3166 2-letter country code.
#
def self.generate(country, *components)
spec = specification(country)
justified = spec.component_lengths.zip(components).map { |length, component| component.rjust(length, "0") }
iban = new(country+'??'+justified.join(''))
iban.update_checksum!
iban
end
# @param [String] countries
# A list of 2 letter country codes. If empty, all countries in
# ISO::IBAN::specifications are used.
#
# @return [ISO::IBAN] A random, valid IBAN
def self.random(*countries)
countries = specifications.keys if countries.empty?
country = countries.sample
account = specification(country).iban_structure.scan(/([A-Z]+)|(\d+)(!?)([nac])/).map { |exact, length, fixed, code|
if exact
exact
elsif code == 'a'
Array.new(length.to_i) { UpperAlpha.sample }.join('')
elsif code == 'c'
Array.new(length.to_i) { AlphaNumeric.sample }.join('')
elsif code == 'e'
' '*length.to_i
elsif code == 'n'
Array.new(length.to_i) { Digits.sample }.join('')
end
}.join('')
account[2,2] = '??'
iban = new(account)
iban.update_checksum!
iban
end
# Converts a String into its digits-only form, i.e. all characters a-z are replaced with their corresponding
# digit sequences, according to the IBAN specification.
#
# @param [String] string
# The string to convert into its numeric form.
#
# @return [String] The string in its numeric, digits-only form.
def self.numerify(string)
string.downcase.gsub(/\D/) { |char|
CharacterCodes.fetch(char) {
raise ArgumentError, "The string contains an invalid character #{char.inspect}"
}
}.to_i
end
# @return [String] The standard form of the IBAN for machine communication, without spaces, encoded in Encoding::BINARY.
attr_reader :compact
# @return [String] The ISO-3166 2-letter country code (first and second character).
attr_reader :country
# @return [ISO::IBAN::Specification] The specification for this IBAN (determined by its country).
attr_reader :specification
# @param [String] iban
# The IBAN number, must be in compact form. Use ISO::IBAN::parse for formatted IBANs.
def initialize(iban)
raise ArgumentError, "String expected for iban, but got #{iban.class}" unless iban.is_a?(String)
@compact = iban.b
@country = iban[0,2]
@specification = self.class.specification(@country, nil)
end
# @example Formatted IBAN
#
# ISO::IBAN.new('CH')
#
# @return [String] The IBAN in its formatted form, which is more human readable than the compact form.
def formatted
@_formatted ||= @compact.gsub(/.{4}(?=.)/, '\0 ')
end
# @return [String]
# IBAN in its numeric form, i.e. all characters a-z are replaced with their corresponding
# digit sequences.
def numeric
@compact.size < 5 ? nil : self.class.numerify(@compact[4..-1]+@compact[0,4])
end
# @return [true, false]
# Whether the IBAN is valid.
# See {#validate} for details.
def valid?
valid_country? && valid_checksum? && valid_length? && valid_format?
end
# @note
# {ISO::IBAN::validate} uses {ISO::IBAN::parse}, which means it will strip whitespace and
# dashes from the IBAN.
# {ISO::IBAN::new} on the other hand expects the IBAN in compact format and will not strip
# those characters.
#
# Validation error codes:
#
# * :invalid_characters
# * :invalid_country
# * :invalid_checksum
# * :invalid_length
# * :invalid_format
#
# Invalid characters means that the IBAN contains characters which are not in the set of A-Za-z0-9. See {#invalid_characters}
# Invalid country means the country is unknown (character 1 & 2 in the IBAN).
# Invalid checksum means the two check digits (character 3 & 4 in the IBAN).
# Invalid length means the IBAN does not comply with the length specified for the country of that IBAN.
# Invalid format means the IBAN does not comply with the format specified for the country of that IBAN.
#
# @return [Array<Symbol>] An array with a code of all validation errors, empty if valid.
def validate
errors = []
errors << :invalid_characters unless valid_characters?
errors << :invalid_country unless valid_country?
errors << :invalid_checksum unless valid_characters? && valid_checksum?
errors << :invalid_length unless valid_length?
errors << :invalid_format unless valid_format?
errors
end
# @return [String] The checksum digits in the IBAN (character 3 & 4).
def checksum_digits
@compact[2,2]
end
# @return [String] The BBAN of the IBAN (everything except the country code and check digits).
def bban
@compact[4..-1]
end
# @return [String, nil] The bank code part of the IBAN, nil if not applicable.
def bank_code
if @specification && @specification.bank_position_from && @specification.bank_position_to
@compact[@specification.bank_position_from..@specification.bank_position_to]
else
nil
end
end
# @return [String, nil] The branch code part of the IBAN, nil if not applicable.
def branch_code
if @specification && @specification.branch_position_from && @specification.branch_position_to
@compact[@specification.branch_position_from..@specification.branch_position_to]
else
nil
end
end
# @return [String] The account code part of the IBAN.
def account_code
@compact[((@specification.branch_position_to || @specification.bank_position_to || 3)+1)..-1]
end
# @example
# invalid = "hägar"
# invalid.encoding # => #<Encoding:UTF-8>
# ISO::IBAN.new(invalid).invalid_characters # => ["\xC3", "\xA4"]
# ISO::IBAN.new(invalid).invalid_characters('utf-8') # => ["ä"]
#
# @param [String, Encoding, nil] input_encoding
# ISO::IBAN::new interprets the passed IBAN as binary.
# If you got the IBAN from a source which is not binary, you should provide that encoding.
# Otherwise an invalid character may be split into multiple bytes.
#
# @return [Array] An Array with all invalid characters.
def invalid_characters(input_encoding=nil)
iban = input_encoding ? @compact.dup.force_encoding(input_encoding) : @compact
iban.gsub(/[A-Z0-9?]*/i, '').chars.uniq
end
# @return [true, false] Whether IBAN consists only of valid characters.
def valid_characters?
@compact =~ /\A[A-Z]{2}(?:\d\d|\?\?)[A-Z0-9]*\z/in ? true : false
end
# @return [true, false] Whether the country of the IBAN is valid.
def valid_country?
@specification ? true : false
end
# @return [true, false] Whether the format of the IBAN is valid.
def valid_format?
@specification && @specification.iban_regex =~ @compact ? true : false
end
# @return [true, false] Whether the length of the IBAN is valid.
def valid_length?
@specification && @compact.size == @specification.iban_length ? true : false
end
# @return [true, false] Whether the checksum of the IBAN is valid.
def valid_checksum?
numerified = numeric()
numerified && (numerified % 97 == 1)
end
# See Object#<=>
#
# @return [-1, 0, 1, nil]
def <=>(other)
other.respond_to?(:compact) ? @compact <=> other.compact : nil
end
# Requires that the checksum digits were left as '??', replaces them with
# the proper checksum.
#
# @return [self]
def update_checksum!
raise "Checksum digit placeholders missing" unless @compact[2,2] == '??'
@compact[2,2] = calculated_check_digits
self
end
# @return [String] The check-digits as calculated from the IBAN.
def calculated_check_digits
"%02d" % (98-(self.class.numerify(bban+@country)*100)%97)
end
# @return [true, false]
# Whether two ISO::IBANs are equal.
# Comparison is based on class and IBAN number
def eql?(other)
self.class.equal?(other.class) && self == other
end
# @return [Integer]
# A hash value, see Object#hash
def hash
[self.class, @compact].hash
end
# See Object#inspect
def inspect
sprintf "#<%p %s>", self.class, formatted
end
# @return [String] The compact form of the IBAN as a String.
def to_s
@compact.dup
end
# @note
# This method is experimental. It might change or be removed in future versions!
#
# @return [Array]
# The individual IBAN components as defined by the SWIFT specification.
# An empty array if this IBAN does not have a specification.
def to_a
@_components ||= @specification ? @compact.match(@specification.iban_regex).captures : []
@_components.dup
end
end
end
|
module JaroWinkler
VERSION = "1.3.0"
end
bump version
module JaroWinkler
VERSION = "1.3.1"
end
|
# encoding: UTF-8
module Jekyll
class Configuration < Hash
# Default options. Overridden by values in _config.yml.
# Strings rather than symbols are used for compatibility with YAML.
DEFAULTS = Configuration[{
# Where things are
'source' => Dir.pwd,
'destination' => File.join(Dir.pwd, '_site'),
'plugins_dir' => '_plugins',
'layouts_dir' => '_layouts',
'data_dir' => '_data',
'includes_dir' => '_includes',
'collections' => {},
# Handling Reading
'safe' => false,
'include' => ['.htaccess'],
'exclude' => [],
'keep_files' => ['.git', '.svn'],
'encoding' => 'utf-8',
'markdown_ext' => 'markdown,mkdown,mkdn,mkd,md',
# Filtering Content
'show_drafts' => nil,
'limit_posts' => 0,
'future' => false,
'unpublished' => false,
# Plugins
'whitelist' => [],
'gems' => [],
# Conversion
'markdown' => 'kramdown',
'highlighter' => 'rouge',
'lsi' => false,
'excerpt_separator' => "\n\n",
'incremental' => false,
# Serving
'detach' => false, # default to not detaching the server
'port' => '4000',
'host' => '127.0.0.1',
'baseurl' => '',
'show_dir_listing' => false,
# Output Configuration
'permalink' => 'date',
'paginate_path' => '/page:num',
'timezone' => nil, # use the local timezone
'quiet' => false,
'verbose' => false,
'defaults' => [],
'rdiscount' => {
'extensions' => []
},
'redcarpet' => {
'extensions' => []
},
'kramdown' => {
'auto_ids' => true,
'toc_levels' => '1..6',
'entity_output' => 'as_char',
'smart_quotes' => 'lsquo,rsquo,ldquo,rdquo',
'input' => "GFM",
'hard_wrap' => false,
'footnote_nr' => 1
}
}.map { |k, v| [k, v.freeze] }].freeze
class << self
# Static: Produce a Configuration ready for use in a Site.
# It takes the input, fills in the defaults where values do not
# exist, and patches common issues including migrating options for
# backwards compatiblity. Except where a key or value is being fixed,
# the user configuration will override the defaults.
#
# user_config - a Hash or Configuration of overrides.
#
# Returns a Configuration filled with defaults and fixed for common
# problems and backwards-compatibility.
def from(user_config)
Utils.deep_merge_hashes(DEFAULTS, Configuration[user_config].stringify_keys).
fix_common_issues.add_default_collections
end
end
# Public: Turn all keys into string
#
# Return a copy of the hash where all its keys are strings
def stringify_keys
reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }
end
def get_config_value_with_override(config_key, override)
override[config_key] || self[config_key] || DEFAULTS[config_key]
end
# Public: Directory of the Jekyll source folder
#
# override - the command-line options hash
#
# Returns the path to the Jekyll source directory
def source(override)
get_config_value_with_override('source', override)
end
def quiet(override = {})
get_config_value_with_override('quiet', override)
end
alias_method :quiet?, :quiet
def verbose(override = {})
get_config_value_with_override('verbose', override)
end
alias_method :verbose?, :verbose
def safe_load_file(filename)
case File.extname(filename)
when /\.toml/i
Jekyll::External.require_with_graceful_fail('toml') unless defined?(TOML)
TOML.load_file(filename)
when /\.ya?ml/i
SafeYAML.load_file(filename) || {}
else
raise ArgumentError, "No parser for '#{filename}' is available. Use a .toml or .y(a)ml file instead."
end
end
# Public: Generate list of configuration files from the override
#
# override - the command-line options hash
#
# Returns an Array of config files
def config_files(override)
# Adjust verbosity quickly
Jekyll.logger.adjust_verbosity(:quiet => quiet?(override), :verbose => verbose?(override))
# Get configuration from <source>/_config.yml or <source>/<config_file>
config_files = override.delete('config')
if config_files.to_s.empty?
default = %w(yml yaml).find(-> { 'yml' }) do |ext|
File.exist?(Jekyll.sanitized_path(source(override), "_config.#{ext}"))
end
config_files = Jekyll.sanitized_path(source(override), "_config.#{default}")
@default_config_file = true
end
config_files = [config_files] unless config_files.is_a? Array
config_files
end
# Public: Read configuration and return merged Hash
#
# file - the path to the YAML file to be read in
#
# Returns this configuration, overridden by the values in the file
def read_config_file(file)
next_config = safe_load_file(file)
check_config_is_hash!(next_config, file)
Jekyll.logger.info "Configuration file:", file
next_config
rescue SystemCallError
if @default_config_file ||= nil
Jekyll.logger.warn "Configuration file:", "none"
{}
else
Jekyll.logger.error "Fatal:", "The configuration file '#{file}' could not be found."
raise LoadError, "The Configuration file '#{file}' could not be found."
end
end
# Public: Read in a list of configuration files and merge with this hash
#
# files - the list of configuration file paths
#
# Returns the full configuration, with the defaults overridden by the values in the
# configuration files
def read_config_files(files)
configuration = clone
begin
files.each do |config_file|
next if config_file.nil? or config_file.empty?
new_config = read_config_file(config_file)
configuration = Utils.deep_merge_hashes(configuration, new_config)
end
rescue ArgumentError => err
Jekyll.logger.warn "WARNING:", "Error reading configuration. " \
"Using defaults (and options)."
$stderr.puts "#{err}"
end
configuration.fix_common_issues.backwards_compatibilize.add_default_collections
end
# Public: Split a CSV string into an array containing its values
#
# csv - the string of comma-separated values
#
# Returns an array of the values contained in the CSV
def csv_to_array(csv)
csv.split(",").map(&:strip)
end
# Public: Ensure the proper options are set in the configuration to allow for
# backwards-compatibility with Jekyll pre-1.0
#
# Returns the backwards-compatible configuration
def backwards_compatibilize
config = clone
# Provide backwards-compatibility
if config.key?('auto') || config.key?('watch')
Jekyll::Deprecator.deprecation_message "Auto-regeneration can no longer" \
" be set from your configuration file(s). Use the"\
" --[no-]watch/-w command-line option instead."
config.delete('auto')
config.delete('watch')
end
if config.key? 'server'
Jekyll::Deprecator.deprecation_message "The 'server' configuration option" \
" is no longer accepted. Use the 'jekyll serve'" \
" subcommand to serve your site with WEBrick."
config.delete('server')
end
renamed_key 'server_port', 'port', config
renamed_key 'plugins', 'plugins_dir', config
renamed_key 'layouts', 'layouts_dir', config
renamed_key 'data_source', 'data_dir', config
if config.key? 'pygments'
Jekyll::Deprecator.deprecation_message "The 'pygments' configuration option" \
" has been renamed to 'highlighter'. Please update your" \
" config file accordingly. The allowed values are 'rouge', " \
"'pygments' or null."
config['highlighter'] = 'pygments' if config['pygments']
config.delete('pygments')
end
%w(include exclude).each do |option|
config[option] ||= []
if config[option].is_a?(String)
Jekyll::Deprecator.deprecation_message "The '#{option}' configuration option" \
" must now be specified as an array, but you specified" \
" a string. For now, we've treated the string you provided" \
" as a list of comma-separated values."
config[option] = csv_to_array(config[option])
end
config[option].map!(&:to_s) if config[option]
end
if (config['kramdown'] || {}).key?('use_coderay')
Jekyll::Deprecator.deprecation_message "Please change 'use_coderay'" \
" to 'enable_coderay' in your configuration file."
config['kramdown']['use_coderay'] = config['kramdown'].delete('enable_coderay')
end
if config.fetch('markdown', 'kramdown').to_s.downcase.eql?("maruku")
Jekyll.logger.abort_with "Error:", "You're using the 'maruku' " \
"Markdown processor, which has been removed as of 3.0.0. " \
"We recommend you switch to Kramdown. To do this, replace " \
"`markdown: maruku` with `markdown: kramdown` in your " \
"`_config.yml` file."
end
config
end
def fix_common_issues
config = clone
if config.key?('paginate') && (!config['paginate'].is_a?(Integer) || config['paginate'] < 1)
Jekyll.logger.warn "Config Warning:", "The `paginate` key must be a" \
" positive integer or nil. It's currently set to '#{config['paginate'].inspect}'."
config['paginate'] = nil
end
config
end
def add_default_collections
config = clone
# It defaults to `{}`, so this is only if someone sets it to null manually.
return config if config['collections'].nil?
# Ensure we have a hash.
if config['collections'].is_a?(Array)
config['collections'] = Hash[config['collections'].map { |c| [c, {}] }]
end
config['collections'] = Utils.deep_merge_hashes(
{ 'posts' => {} }, config['collections']
).tap do |collections|
collections['posts']['output'] = true
if config['permalink']
collections['posts']['permalink'] ||= style_to_permalink(config['permalink'])
end
end
config
end
def renamed_key(old, new, config, _ = nil)
if config.key?(old)
Jekyll::Deprecator.deprecation_message "The '#{old}' configuration" \
" option has been renamed to '#{new}'. Please update your config" \
" file accordingly."
config[new] = config.delete(old)
end
end
private
def style_to_permalink(permalink_style)
case permalink_style.to_sym
when :pretty
"/:categories/:year/:month/:day/:title/"
when :none
"/:categories/:title:output_ext"
when :date
"/:categories/:year/:month/:day/:title:output_ext"
when :ordinal
"/:categories/:year/:y_day/:title:output_ext"
else
permalink_style.to_s
end
end
# Private: Checks if a given config is a hash
#
# extracted_config - the value to check
# file - the file from which the config was extracted
#
# Raises an ArgumentError if given config is not a hash
def check_config_is_hash!(extracted_config, file)
unless extracted_config.is_a?(Hash)
raise ArgumentError.new("Configuration file: (INVALID) #{file}".yellow)
end
end
end
end
Don't default 'include' and 'exclude' to an empty array
# encoding: UTF-8
module Jekyll
class Configuration < Hash
# Default options. Overridden by values in _config.yml.
# Strings rather than symbols are used for compatibility with YAML.
DEFAULTS = Configuration[{
# Where things are
'source' => Dir.pwd,
'destination' => File.join(Dir.pwd, '_site'),
'plugins_dir' => '_plugins',
'layouts_dir' => '_layouts',
'data_dir' => '_data',
'includes_dir' => '_includes',
'collections' => {},
# Handling Reading
'safe' => false,
'include' => ['.htaccess'],
'exclude' => [],
'keep_files' => ['.git', '.svn'],
'encoding' => 'utf-8',
'markdown_ext' => 'markdown,mkdown,mkdn,mkd,md',
# Filtering Content
'show_drafts' => nil,
'limit_posts' => 0,
'future' => false,
'unpublished' => false,
# Plugins
'whitelist' => [],
'gems' => [],
# Conversion
'markdown' => 'kramdown',
'highlighter' => 'rouge',
'lsi' => false,
'excerpt_separator' => "\n\n",
'incremental' => false,
# Serving
'detach' => false, # default to not detaching the server
'port' => '4000',
'host' => '127.0.0.1',
'baseurl' => '',
'show_dir_listing' => false,
# Output Configuration
'permalink' => 'date',
'paginate_path' => '/page:num',
'timezone' => nil, # use the local timezone
'quiet' => false,
'verbose' => false,
'defaults' => [],
'rdiscount' => {
'extensions' => []
},
'redcarpet' => {
'extensions' => []
},
'kramdown' => {
'auto_ids' => true,
'toc_levels' => '1..6',
'entity_output' => 'as_char',
'smart_quotes' => 'lsquo,rsquo,ldquo,rdquo',
'input' => "GFM",
'hard_wrap' => false,
'footnote_nr' => 1
}
}.map { |k, v| [k, v.freeze] }].freeze
class << self
# Static: Produce a Configuration ready for use in a Site.
# It takes the input, fills in the defaults where values do not
# exist, and patches common issues including migrating options for
# backwards compatiblity. Except where a key or value is being fixed,
# the user configuration will override the defaults.
#
# user_config - a Hash or Configuration of overrides.
#
# Returns a Configuration filled with defaults and fixed for common
# problems and backwards-compatibility.
def from(user_config)
Utils.deep_merge_hashes(DEFAULTS, Configuration[user_config].stringify_keys).
fix_common_issues.add_default_collections
end
end
# Public: Turn all keys into string
#
# Return a copy of the hash where all its keys are strings
def stringify_keys
reduce({}) { |hsh, (k, v)| hsh.merge(k.to_s => v) }
end
def get_config_value_with_override(config_key, override)
override[config_key] || self[config_key] || DEFAULTS[config_key]
end
# Public: Directory of the Jekyll source folder
#
# override - the command-line options hash
#
# Returns the path to the Jekyll source directory
def source(override)
get_config_value_with_override('source', override)
end
def quiet(override = {})
get_config_value_with_override('quiet', override)
end
alias_method :quiet?, :quiet
def verbose(override = {})
get_config_value_with_override('verbose', override)
end
alias_method :verbose?, :verbose
def safe_load_file(filename)
case File.extname(filename)
when /\.toml/i
Jekyll::External.require_with_graceful_fail('toml') unless defined?(TOML)
TOML.load_file(filename)
when /\.ya?ml/i
SafeYAML.load_file(filename) || {}
else
raise ArgumentError, "No parser for '#{filename}' is available. Use a .toml or .y(a)ml file instead."
end
end
# Public: Generate list of configuration files from the override
#
# override - the command-line options hash
#
# Returns an Array of config files
def config_files(override)
# Adjust verbosity quickly
Jekyll.logger.adjust_verbosity(:quiet => quiet?(override), :verbose => verbose?(override))
# Get configuration from <source>/_config.yml or <source>/<config_file>
config_files = override.delete('config')
if config_files.to_s.empty?
default = %w(yml yaml).find(-> { 'yml' }) do |ext|
File.exist?(Jekyll.sanitized_path(source(override), "_config.#{ext}"))
end
config_files = Jekyll.sanitized_path(source(override), "_config.#{default}")
@default_config_file = true
end
config_files = [config_files] unless config_files.is_a? Array
config_files
end
# Public: Read configuration and return merged Hash
#
# file - the path to the YAML file to be read in
#
# Returns this configuration, overridden by the values in the file
def read_config_file(file)
next_config = safe_load_file(file)
check_config_is_hash!(next_config, file)
Jekyll.logger.info "Configuration file:", file
next_config
rescue SystemCallError
if @default_config_file ||= nil
Jekyll.logger.warn "Configuration file:", "none"
{}
else
Jekyll.logger.error "Fatal:", "The configuration file '#{file}' could not be found."
raise LoadError, "The Configuration file '#{file}' could not be found."
end
end
# Public: Read in a list of configuration files and merge with this hash
#
# files - the list of configuration file paths
#
# Returns the full configuration, with the defaults overridden by the values in the
# configuration files
def read_config_files(files)
configuration = clone
begin
files.each do |config_file|
next if config_file.nil? or config_file.empty?
new_config = read_config_file(config_file)
configuration = Utils.deep_merge_hashes(configuration, new_config)
end
rescue ArgumentError => err
Jekyll.logger.warn "WARNING:", "Error reading configuration. " \
"Using defaults (and options)."
$stderr.puts "#{err}"
end
configuration.fix_common_issues.backwards_compatibilize.add_default_collections
end
# Public: Split a CSV string into an array containing its values
#
# csv - the string of comma-separated values
#
# Returns an array of the values contained in the CSV
def csv_to_array(csv)
csv.split(",").map(&:strip)
end
# Public: Ensure the proper options are set in the configuration to allow for
# backwards-compatibility with Jekyll pre-1.0
#
# Returns the backwards-compatible configuration
def backwards_compatibilize
config = clone
# Provide backwards-compatibility
if config.key?('auto') || config.key?('watch')
Jekyll::Deprecator.deprecation_message "Auto-regeneration can no longer" \
" be set from your configuration file(s). Use the"\
" --[no-]watch/-w command-line option instead."
config.delete('auto')
config.delete('watch')
end
if config.key? 'server'
Jekyll::Deprecator.deprecation_message "The 'server' configuration option" \
" is no longer accepted. Use the 'jekyll serve'" \
" subcommand to serve your site with WEBrick."
config.delete('server')
end
renamed_key 'server_port', 'port', config
renamed_key 'plugins', 'plugins_dir', config
renamed_key 'layouts', 'layouts_dir', config
renamed_key 'data_source', 'data_dir', config
if config.key? 'pygments'
Jekyll::Deprecator.deprecation_message "The 'pygments' configuration option" \
" has been renamed to 'highlighter'. Please update your" \
" config file accordingly. The allowed values are 'rouge', " \
"'pygments' or null."
config['highlighter'] = 'pygments' if config['pygments']
config.delete('pygments')
end
%w(include exclude).each do |option|
if config[option].is_a?(String)
Jekyll::Deprecator.deprecation_message "The '#{option}' configuration option" \
" must now be specified as an array, but you specified" \
" a string. For now, we've treated the string you provided" \
" as a list of comma-separated values."
config[option] = csv_to_array(config[option])
end
config[option].map!(&:to_s) if config[option]
end
if (config['kramdown'] || {}).key?('use_coderay')
Jekyll::Deprecator.deprecation_message "Please change 'use_coderay'" \
" to 'enable_coderay' in your configuration file."
config['kramdown']['use_coderay'] = config['kramdown'].delete('enable_coderay')
end
if config.fetch('markdown', 'kramdown').to_s.downcase.eql?("maruku")
Jekyll.logger.abort_with "Error:", "You're using the 'maruku' " \
"Markdown processor, which has been removed as of 3.0.0. " \
"We recommend you switch to Kramdown. To do this, replace " \
"`markdown: maruku` with `markdown: kramdown` in your " \
"`_config.yml` file."
end
config
end
def fix_common_issues
config = clone
if config.key?('paginate') && (!config['paginate'].is_a?(Integer) || config['paginate'] < 1)
Jekyll.logger.warn "Config Warning:", "The `paginate` key must be a" \
" positive integer or nil. It's currently set to '#{config['paginate'].inspect}'."
config['paginate'] = nil
end
config
end
def add_default_collections
config = clone
# It defaults to `{}`, so this is only if someone sets it to null manually.
return config if config['collections'].nil?
# Ensure we have a hash.
if config['collections'].is_a?(Array)
config['collections'] = Hash[config['collections'].map { |c| [c, {}] }]
end
config['collections'] = Utils.deep_merge_hashes(
{ 'posts' => {} }, config['collections']
).tap do |collections|
collections['posts']['output'] = true
if config['permalink']
collections['posts']['permalink'] ||= style_to_permalink(config['permalink'])
end
end
config
end
def renamed_key(old, new, config, _ = nil)
if config.key?(old)
Jekyll::Deprecator.deprecation_message "The '#{old}' configuration" \
" option has been renamed to '#{new}'. Please update your config" \
" file accordingly."
config[new] = config.delete(old)
end
end
private
def style_to_permalink(permalink_style)
case permalink_style.to_sym
when :pretty
"/:categories/:year/:month/:day/:title/"
when :none
"/:categories/:title:output_ext"
when :date
"/:categories/:year/:month/:day/:title:output_ext"
when :ordinal
"/:categories/:year/:y_day/:title:output_ext"
else
permalink_style.to_s
end
end
# Private: Checks if a given config is a hash
#
# extracted_config - the value to check
# file - the file from which the config was extracted
#
# Raises an ArgumentError if given config is not a hash
def check_config_is_hash!(extracted_config, file)
unless extracted_config.is_a?(Hash)
raise ArgumentError.new("Configuration file: (INVALID) #{file}".yellow)
end
end
end
end
|
# coding: iso-8859-1
#
# Copyright (c) 2015 Jani J. Hakala <jjhakala@gmail.com> Jyvskyl, Finland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3 of the
# License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
GRID = "000704005020010070000080002090006250600070008053200010400090000030060090200407000"
UNSOLVED = nil
if GRID.length != 81
puts "Bad input"
exit
end
class Pos
attr_accessor :row, :column, :box_number
def initialize(row, col)
@row = row
@column = col
n = (((row - 1) / 3) * 3 + ((column - 1) / 3))
@box_number = n + 1
end
def same_row?(other)
@row == other.row
end
def same_column?(other)
@column == other.column
end
def same_box?(other)
self.box_number == other.box_number
end
def to_s
"#{@row} #{@column}"
end
def ==(other)
self.class == other.class and
self.row == other.row and
self.column == other.column
end
def hash
@row.hash ^ @column.hash
end
alias eql? ==
end
class Cell
attr_accessor :pos, :value
def initialize(pos, value)
@pos = pos
@value = value
end
def solved?
@value > 0
end
def to_s
"#{@pos.row} #{@pos.column} #{@value}"
end
def ==(other)
self.class == other.class and
self.pos == other.pos and
self.value == other.value
end
alias eql? ==
end
class Solver
attr_accessor :grid, :rows, :columns, :boxes, :candidates
def initialize(str)
@grid = string_to_grid(str)
@candidates = []
self.init
end
def init_solved
@solved = []
@grid.each do |pos, cell|
if cell.solved?
@solved.push Cell.new(cell.pos, cell.value)
end
end
end
def init_unsolved
@unsolved = []
@grid.each do |pos, cell|
if not cell.solved?
@unsolved.push Cell.new(cell.pos, cell.value)
end
end
end
def init
# Remove candidates removable because of initially solved grid
self.init_solved
self.init_unsolved
@candidates = []
@unsolved.each do |cell|
(1..9).each do |i|
candidates.push Cell.new(cell.pos, i)
end
end
@solved.each do |cell|
# puts "Solved: #{cell}"
self.update_cell(cell)
end
end
def update_cell(cell)
candidates.reject! { |cell2| cell.pos == cell2.pos }
candidates.reject! do |cell2|
cell.pos != cell2.pos and cell.value == cell2.value and
(cell.pos.row == cell2.pos.row or
cell.pos.column == cell2.pos.column or
cell.pos.box_number == cell2.pos.box_number)
end
end
def solve
puts "Start solving"
finders = [
proc {|s| self.find_singles_simple()},
proc {|s| self.find_singles()},
proc {|s| self.find_naked_pairs()}
]
while 1
found = []
finders.each do |finder|
found = finder.call()
if found.length > 0
puts "Something found"
break
else
puts "Nothing found"
end
end
if found.length > 0
next
end
puts "No progress"
break
end
end
# To be called with solved cells
def update_grid(found)
found.each do |x|
puts "Solved: #{x}"
cell = @grid[x.pos]
cell.value = x.value
@solved.push cell
@unsolved.reject! { |xx| xx.pos == x.pos }
self.update_cell(x)
end
end
def update_candidates(found)
# old = @candidates.dup
@candidates.reject! { |x| found.include? x }
# found.each do |cell|
# if not flag
# flag = (x.pos == cell.pos and x.value == cell.value)
# break
# end
# end
# flag
# end
# diff = old - @candidates
# puts "diff #{diff}"
end
def get_row (i)
@candidates.select { |cell| cell.pos.row == i }
end
def get_column (i)
@candidates.select { |cell| cell.pos.column == i }
end
def get_box (i)
@candidates.select { |cell| cell.pos.box_number == i }
end
def eliminator (fun)
found = []
(1..9).each do |i|
found = found + fun.call(self.get_row(i))
found = found + fun.call(self.get_column(i))
found = found + fun.call(self.get_box(i))
end
found.uniq! {|x| x.pos}
found.each do |x|
puts "eliminator found: #{x}"
end
found
end
def find_singles_simple
puts "Find singles simple"
def dummy(set)
found = []
# Unique positions
poss = set.map { |x| x.pos }
poss.uniq!
# puts "positions #{poss.length}"
poss.each do |pos|
cands = set.select { |x| x.pos == pos }
# puts "cands #{cands.length}"
if cands.length == 1
found.push(cands[0].dup)
end
end
found
end
found = eliminator proc { |set| dummy(set) }
if found.length > 0
found.each do |x|
puts "find_singles_simple #{x}"
end
self.update_grid(found)
# self.update_candidates(found)
end
found
end
def find_singles
puts "Find singles"
def dummy(set)
nums = []
found = []
set.each do |cell|
# puts "find_singles cell #{cell.pos}, value #{cell.value}"
nums = nums | [cell.value]
end
nums.sort!
# puts "Numbers #{nums}"
nums.each do |x|
nset = set.select { |cell| cell.value == x }
# puts "nums #{nset.length}"
if nset.length == 1
found = found | [ nset[0].dup ]
end
end
found
end
found = eliminator proc { |set| dummy(set) }
if found.length > 0
found.each do |x|
puts "find_singles #{x}"
end
self.update_grid(found)
# self.update_candidates(found)
end
found
end
def find_naked_pairs
puts "Find naked pairs"
def dummy(set)
nums = []
found = []
set.each { |cell| nums = nums | [cell.value] }
nums.sort!
if nums.length < 2
# puts "Too short set #{set}"
return []
end
poss = set.map { |x| x.pos }
poss.uniq!
if poss.length < 3
# Nothing to be gained
return []
end
nums.combination(2) do |c|
hits = poss.select do |pos|
nset = set.select { |cell| cell.pos == pos }
if nset.length == 2
nums = nset.map { |x| x.value }
c == nums
else
false
end
end
if hits.length == 2
tmp = set.select do |cell|
not hits.include? cell.pos and c.include? cell.value
end
found = found | tmp
end
end
found
end
found = eliminator proc { |set| dummy(set) }
if found.length > 0
found.each do |x|
puts "find_naked_pairs #{x}"
end
self.update_candidates(found)
end
found
end
def find_triples
[]
end
def find_quads
[]
end
end
def string_to_grid(str)
i = 1
j = 1
grid = Hash.new
str.each_char do |c|
val = Integer(c)
pos = Pos.new(i, j)
cell = Cell.new(pos, val)
grid[pos] = cell
j += 1
if (j % 10) == 0
i += 1
j = 1
end
end
grid
end
puts GRID
solver = Solver.new GRID
solver.solve
# strategies = [ ["singles", eliminateSingles],
# ["naked pairs", eliminatePairs],
# ["naked triples", eliminateTriples],
# ["naked quads", eliminateQuads],
# ["pointing pairs", eliminatePointingPairs],
# ["box line reduction", eliminateBoxLineReduction],
# ["X-wing", eliminateXWings],
# ["Y-wing", eliminateYWings],
# ["XYZ-wing", eliminateXYZWings]]
# puts solved
# solved.each
# puts candidates
Add helper function and rename methods
# coding: iso-8859-1
#
# Copyright (c) 2015 Jani J. Hakala <jjhakala@gmail.com> Jyvskyl, Finland
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, version 3 of the
# License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
GRID = "000704005020010070000080002090006250600070008053200010400090000030060090200407000"
UNSOLVED = nil
if GRID.length != 81
puts "Bad input"
exit
end
class Pos
attr_accessor :row, :column, :box_number
def initialize(row, col)
@row = row
@column = col
n = (((row - 1) / 3) * 3 + ((column - 1) / 3))
@box_number = n + 1
end
def same_row?(other)
@row == other.row
end
def same_column?(other)
@column == other.column
end
def same_box?(other)
self.box_number == other.box_number
end
def to_s
"#{@row} #{@column}"
end
def ==(other)
self.class == other.class and
self.row == other.row and
self.column == other.column
end
def hash
@row.hash ^ @column.hash
end
alias eql? ==
end
class Cell
attr_accessor :pos, :value
def initialize(pos, value)
@pos = pos
@value = value
end
def solved?
@value > 0
end
def to_s
"#{@pos.row} #{@pos.column} #{@value}"
end
def ==(other)
self.class == other.class and
self.pos == other.pos and
self.value == other.value
end
alias eql? ==
end
class Solver
attr_accessor :grid, :rows, :columns, :boxes, :candidates
def initialize(str)
@grid = string_to_grid(str)
@candidates = []
self.init
end
def init_solved
@solved = []
@grid.each do |pos, cell|
if cell.solved?
@solved.push Cell.new(cell.pos, cell.value)
end
end
end
def init_unsolved
@unsolved = []
@grid.each do |pos, cell|
if not cell.solved?
@unsolved.push Cell.new(cell.pos, cell.value)
end
end
end
def init
# Remove candidates removable because of initially solved grid
self.init_solved
self.init_unsolved
@candidates = []
@unsolved.each do |cell|
(1..9).each do |i|
candidates.push Cell.new(cell.pos, i)
end
end
@solved.each do |cell|
# puts "Solved: #{cell}"
self.update_cell(cell)
end
end
def update_cell(cell)
candidates.reject! { |cell2| cell.pos == cell2.pos }
candidates.reject! do |cell2|
cell.pos != cell2.pos and cell.value == cell2.value and
(cell.pos.row == cell2.pos.row or
cell.pos.column == cell2.pos.column or
cell.pos.box_number == cell2.pos.box_number)
end
end
def solve
puts "Start solving"
finders = [
proc {|s| self.find_singles_simple()},
proc {|s| self.find_singles()},
proc {|s| self.find_naked_pairs()},
proc {|s| self.find_pointing_pairs()}
]
while 1
found = []
finders.each do |finder|
found = finder.call()
if found.length > 0
puts "Something found"
break
else
puts "Nothing found"
end
end
if found.length > 0
next
end
puts "No progress"
break
end
end
# To be called with solved cells
def update_grid(found)
found.each do |x|
puts "Solved: #{x}"
cell = @grid[x.pos]
cell.value = x.value
@solved.push cell
@unsolved.reject! { |xx| xx.pos == x.pos }
self.update_cell(x)
end
end
def update_candidates(found)
# old = @candidates.dup
@candidates.reject! { |x| found.include? x }
# found.each do |cell|
# if not flag
# flag = (x.pos == cell.pos and x.value == cell.value)
# break
# end
# end
# flag
# end
# diff = old - @candidates
# puts "diff #{diff}"
end
def get_row (i)
@candidates.select { |cell| cell.pos.row == i }
end
def get_column (i)
@candidates.select { |cell| cell.pos.column == i }
end
def get_box (i)
@candidates.select { |cell| cell.pos.box_number == i }
end
def eliminator (fun)
found = []
(1..9).each do |i|
found = found + fun.call(self.get_row(i))
found = found + fun.call(self.get_column(i))
found = found + fun.call(self.get_box(i))
end
found.uniq! {|x| x.pos}
found.each do |x|
puts "eliminator found: #{x}"
end
found
end
def find_singles_simple
puts "Find singles simple"
def dummy(set)
found = []
# Unique positions
poss = set.map { |x| x.pos }
poss.uniq!
# puts "positions #{poss.length}"
poss.each do |pos|
cands = set.select { |x| x.pos == pos }
# puts "cands #{cands.length}"
if cands.length == 1
found.push(cands[0].dup)
end
end
found
end
found = eliminator proc { |set| dummy(set) }
if found.length > 0
found.each do |x|
puts "find_singles_simple #{x}"
end
self.update_grid(found)
# self.update_candidates(found)
end
found
end
def find_singles
puts "Find singles"
def dummy(set)
nums = unique_numbers(set)
found = []
nums.sort!
# puts "Numbers #{nums}"
nums.each do |x|
nset = set.select { |cell| cell.value == x }
# puts "nums #{nset.length}"
if nset.length == 1
found = found | [ nset[0].dup ]
end
end
found
end
found = eliminator proc { |set| dummy(set) }
if found.length > 0
found.each do |x|
puts "find_singles #{x}"
end
self.update_grid(found)
# self.update_candidates(found)
end
found
end
def find_naked_pairs
puts "Find naked pairs"
def dummy(set)
nums = unique_numbers(set)
found = []
if nums.length < 2
# puts "Too short set #{set}"
return []
end
poss = set.map { |x| x.pos }
poss.uniq!
if poss.length < 3
# Nothing to be gained
return []
end
nums.combination(2) do |c|
hits = poss.select do |pos|
nset = set.select { |cell| cell.pos == pos }
if nset.length == 2
nums = nset.map { |x| x.value }
c == nums
else
false
end
end
if hits.length == 2
tmp = set.select do |cell|
not hits.include? cell.pos and c.include? cell.value
end
found = found | tmp
end
end
found
end
found = eliminator proc { |set| dummy(set) }
if found.length > 0
found.each do |x|
puts "find_naked_pairs #{x}"
end
self.update_candidates(found)
end
found
end
def find_naked_triples
[]
end
def find_naked_quads
[]
end
def find_pointing_pairs
[]
end
end
def unique_numbers(set)
nums = []
set.each { |cell| nums = nums | [cell.value] }
nums.sort!
nums
end
def string_to_grid(str)
i = 1
j = 1
grid = Hash.new
str.each_char do |c|
val = Integer(c)
pos = Pos.new(i, j)
cell = Cell.new(pos, val)
grid[pos] = cell
j += 1
if (j % 10) == 0
i += 1
j = 1
end
end
grid
end
puts GRID
solver = Solver.new GRID
solver.solve
# strategies = [ ["singles", eliminateSingles],
# ["naked pairs", eliminatePairs],
# ["naked triples", eliminateTriples],
# ["naked quads", eliminateQuads],
# ["pointing pairs", eliminatePointingPairs],
# ["box line reduction", eliminateBoxLineReduction],
# ["X-wing", eliminateXWings],
# ["Y-wing", eliminateYWings],
# ["XYZ-wing", eliminateXYZWings]]
# puts solved
# solved.each
# puts candidates
|
module Kafka
class OffsetManager
def initialize(group:, logger:, commit_interval:, commit_threshold:)
@group = group
@logger = logger
@commit_interval = commit_interval
@commit_threshold = commit_threshold
@uncommitted_offsets = 0
@processed_offsets = {}
@default_offsets = {}
@committed_offsets = nil
@last_commit = Time.at(0)
end
def set_default_offset(topic, default_offset)
@default_offsets[topic] = default_offset
end
def mark_as_processed(topic, partition, offset)
@uncommitted_offsets += 1
@processed_offsets[topic] ||= {}
@processed_offsets[topic][partition] = offset + 1
end
def next_offset_for(topic, partition)
offset = @processed_offsets.fetch(topic, {}).fetch(partition) {
committed_offset_for(topic, partition)
}
offset = @default_offsets.fetch(topic) if offset < 0
offset
end
def commit_offsets
unless @processed_offsets.empty?
@logger.info "Committing offsets for #{@uncommitted_offsets} messages"
@group.commit_offsets(@processed_offsets)
@last_commit = Time.now
@processed_offsets.clear
@uncommitted_offsets = 0
end
end
def commit_offsets_if_necessary
if seconds_since_last_commit >= @commit_interval || commit_threshold_reached?
commit_offsets
end
end
def clear_offsets
@uncommitted_offsets = 0
@processed_offsets.clear
@committed_offsets = nil
end
private
def seconds_since_last_commit
Time.now - @last_commit
end
def committed_offset_for(topic, partition)
@committed_offsets ||= @group.fetch_offsets
@committed_offsets.offset_for(topic, partition)
end
def commit_threshold_reached?
@commit_threshold != 0 && @uncommitted_offsets >= @commit_threshold
end
end
end
Don't use stale offset information when consuming messages (#174)
* Don't use stale offset information when consuming messages
After committing offsets, the consumer would clear the information of
which offsets had been processed but fail to refresh the broker supplied
table, leading to erroneous offset information.
* Only clear consumer offsets when re-joining a group
Clearing on every commit is wasteful.
module Kafka
class OffsetManager
def initialize(group:, logger:, commit_interval:, commit_threshold:)
@group = group
@logger = logger
@commit_interval = commit_interval
@commit_threshold = commit_threshold
@uncommitted_offsets = 0
@processed_offsets = {}
@default_offsets = {}
@committed_offsets = nil
@last_commit = Time.at(0)
end
def set_default_offset(topic, default_offset)
@default_offsets[topic] = default_offset
end
def mark_as_processed(topic, partition, offset)
@uncommitted_offsets += 1
@processed_offsets[topic] ||= {}
@processed_offsets[topic][partition] = offset + 1
end
def next_offset_for(topic, partition)
offset = @processed_offsets.fetch(topic, {}).fetch(partition) {
committed_offset_for(topic, partition)
}
offset = @default_offsets.fetch(topic) if offset < 0
offset
end
def commit_offsets
unless @processed_offsets.empty?
@logger.info "Committing offsets for #{@uncommitted_offsets} messages"
@group.commit_offsets(@processed_offsets)
@last_commit = Time.now
@uncommitted_offsets = 0
end
end
def commit_offsets_if_necessary
if seconds_since_last_commit >= @commit_interval || commit_threshold_reached?
commit_offsets
end
end
def clear_offsets
@uncommitted_offsets = 0
@processed_offsets.clear
@committed_offsets = nil
end
private
def seconds_since_last_commit
Time.now - @last_commit
end
def committed_offset_for(topic, partition)
@committed_offsets ||= @group.fetch_offsets
@committed_offsets.offset_for(topic, partition)
end
def commit_threshold_reached?
@commit_threshold != 0 && @uncommitted_offsets >= @commit_threshold
end
end
end
|
# TODO: Add .first_par class to first paragraph
require 'kramdown/document'
module Kramdown
module Parser
# Parses DOCX XML string to kramdown AT
#
# Naming conventions
#
# * node: refers to a Nokogiri::XML::Node (XML space)
# * element: refers to a Kramdown::Element (kramdown space). Note that we actually
# use a sub-class named Kramdown::ElementRt
# * ke: l_var that refers to a kramdown element
# * xn: l_var that refers to an XML node
class Docx
include Kramdown::AdjacentElementMerger
include Kramdown::ImportWhitespaceSanitizer
include Kramdown::NestedEmsProcessor
include Kramdown::TreeCleaner
include Kramdown::WhitespaceOutPusher
# Custom error
class InvalidElementException < RuntimeError; end
# Represents a TextRunFormat's attributes.
# @attr_reader bold [Boolean]
# @attr_reader italic [Boolean]
# @attr_reader smcaps [Boolean]
# @attr_reader subscript [Boolean]
# @attr_reader superscript [Boolean]
# @attr_reader underline [Boolean]
class TextRunFormatAttrs
SUPPORTED_TEXT_RUN_FORMAT_ATTRS = %i[
bold
italic
smcaps
subscript
superscript
underline
].sort
attr_reader *SUPPORTED_TEXT_RUN_FORMAT_ATTRS
# @param text_run [Nokogiri::XML::Node] the text_run's XML node
def initialize(text_run)
tr_style = text_run.at_xpath('./w:rPr')
if tr_style
# NOTE: w:b, w:i, and w:smallCaps are supposed to be a toggle properties
# (<w:b/>), however in some DOCX documents (ODT -> DOC -> DOCX), they
# have an unexpected `val` attribute that we need to check
# (<w:b w:val="false"/>). They could also be set to '0' if saved from MS Word.
@bold = (xn = tr_style.at_xpath('./w:b')) && !%w[false 0].include?(xn['w:val'])
@italic = (xn = tr_style.at_xpath('./w:i')) && !%w[false 0].include?(xn['w:val'])
@smcaps = (xn = tr_style.at_xpath('./w:smallCaps')) && !%w[false 0].include?(xn['w:val'])
@subscript = tr_style.at_xpath("./w:vertAlign[@w:val='subscript']")
@superscript = tr_style.at_xpath("./w:vertAlign[@w:val='superscript']")
@underline = (xn = tr_style.at_xpath('./w:u')) && 'none' != xn['w:val'] # val 'none' turns off underline
end
end
# Returns an array with symbols of all applied attributes, sorted
# alphabetically
def applied_attrs
@applied_attrs ||= SUPPORTED_TEXT_RUN_FORMAT_ATTRS.find_all { |e|
self.send(e)
}
end
end
# The hash with the parsing options.
attr_reader :options
# The array with the parser warnings.
attr_reader :warnings
# The original source string.
attr_reader :source
# The root element of element tree that is created from the source string.
attr_reader :root
# Maps DOCX paragraph style ids to kramdown elements
# @return [Hash] Hash with paragraph style ids as keys and arrays with the
# following items as values:
# * element type: a supported Kramdown::Element type
# * element value: String or nil
# * element attr: Hash or nil.
# * element options (can contain a lambda for lazy execution, gets passed the para XML node)
def self.paragraph_style_mappings
{
"header1" => [:header, nil, { } , lambda { |para| {:level => 1, :raw_text => para.text} }],
"header2" => [:header, nil, { } , lambda { |para| {:level => 2, :raw_text => para.text} }],
"header3" => [:header, nil, { } , lambda { |para| {:level => 3, :raw_text => para.text} }],
"normal" => [:p , nil, {'class' => 'normal'} , nil],
"paraTest" => [:p , nil, {'class' => 'para_test'} , nil],
"horizontalRule" => [:hr , nil, { } , nil],
}
end
# Parse the +source+ string into an element tree, possibly using the parsing +options+, and
# return the root element of the element tree and an array with warning messages.
# @param source [String] contents of word/document.xml as string
# @param options [Hash, optional] these will be passed to Kramdown::Parser instance
def self.parse(source, options = {})
parser = new(source, options)
parser.parse
[parser.root, parser.warnings]
end
# @note We change the default kramdown parser behavior where you can't
# just create a parser instance. This makes it easier to use this parser
# for validation purpose, and to tie it into our workflows.
#
# @param source [String] contents of word/document.xml as string
# @param options [Hash, optional] these will be passed to Kramdown::Parser
def initialize(source, options)
@source = source
@options = {
:line_width => 100000, # set to very large value so that each para is on a single line
:input => 'KramdownRepositext' # that is what we generate as string below
}.merge(options)
@root = nil
@warnings = []
end
# Parses @source into a Kramdown tree under @root.
def parse
@root = Kramdown::ElementRt.new(
:root, nil, nil, :encoding => 'UTF-8', :location => { :line => 1 }
)
@ke_context = Folio::KeContext.new({ 'root' => @root }, self)
# Transform the XML tree
xml_document = Nokogiri::XML(@source) { |config| config.noblanks }
body_xn = xml_document.at_xpath('//w:document//w:body')
body_xn.children.each do |child_xn|
process_xml_node(child_xn)
end
post_process_kramdown_tree!(@ke_context.get('root', nil))
end
# @param [Nokogiri::XML::Node] xn the XML Node to process
# @param [String] message
def add_warning(xn, message)
if '' != message.to_s
@warnings << {
message: message,
line: xn.line,
path: xn.name_and_class_path
}
end
end
private
# Processes an xml_node
# @param xn [Nokogiri::XML::Node] the XML Node to process
def process_xml_node(xn)
raise(InvalidElementException, "xn cannot be nil") if xn.nil?
# TODO: Don't use OpenStruct here for performance reasons.
@xn_context = OpenStruct.new(
:match_found => false,
:process_children => true,
)
if xn.duplicate_of?(xn.parent)
# xn is duplicate of its parent, pull it
pull_node(xn)
@xn_context.match_found = true
else
method_name = "process_node_#{ xn.name.downcase.gsub('-', '_') }"
if respond_to?(method_name, true)
self.send(method_name, xn)
else
raise InvalidElementException.new(
"Unexpected element type #{ xn.name } on line #{ xn.line }. Requires method #{ method_name.inspect }."
)
end
end
if !@xn_context.match_found
add_warning(xn, "Unhandled XML node #{ xn.name_and_class }")
end
# recurse over child XML Nodes
if @xn_context.process_children
xn.children.each { |xnc| process_xml_node(xnc) }
end
end
# Modifies kramdown_tree in place.
# NOTE: this method has potential for optimization. We blindly run
# recursively_merge_adjacent_elements in a number of places. This is only
# necessary if the previous methods actually modified the tree.
# I'm thinking only if nodes were removed, however that needs to be
# confirmed.
# @param kramdown_tree [Kramdown::Element] the root of the tree
def post_process_kramdown_tree!(kramdown_tree)
# override this to post process elements in the kramdown tree
# NOTE: It's important to call the methods below for correct results.
# You have two options:
# 1. call super if you override this method
# 2. copy the methods below into your own method if you need different sequence
recursively_merge_adjacent_elements!(kramdown_tree)
recursively_clean_up_nested_ems!(kramdown_tree) # has to be called after process_temp_em_class
recursively_push_out_whitespace!(kramdown_tree)
# needs to run after whitespace has been pushed out so that we won't
# have a leading \t inside an :em that is the first child in a para.
# After whitespace is pushed out, the \t will be a direct :text child
# of :p and first char will be easy to detect.
recursively_sanitize_whitespace_during_import!(kramdown_tree)
# merge again since we may have new identical siblings after all the
# other processing.
recursively_merge_adjacent_elements!(kramdown_tree)
recursively_clean_up_tree!(kramdown_tree)
# Run this again since we may have new locations with leading or trailing whitespace
recursively_sanitize_whitespace_during_import!(kramdown_tree)
# merge again since we may have new identical siblings after cleaning up the tree
# e.g. an italic span with whitespace only between two text nodes was removed.
recursively_merge_adjacent_elements!(kramdown_tree)
# DOCX import specific cleanup
recursively_post_process_tree!(kramdown_tree)
end
# ***********************************************
# Node type specific processors
# ***********************************************
def process_node_bookmarkend(xn)
# bookmarkEnd
ignore_node(xn)
flag_match_found
end
def process_node_bookmarkstart(xn)
# bookmarkStart
ignore_node(xn)
flag_match_found
end
def process_node_commentrangestart(xn)
# commentRangeStart
ignore_node(xn)
flag_match_found
end
def process_node_commentrangeend(xn)
# commentRangeEnd
ignore_node(xn)
flag_match_found
end
def process_node_commentreference(xn)
# commentReference
ignore_node(xn)
flag_match_found
end
def process_node_del(xn)
# Change tracking: Deletion. Ignore this node.
# See process_node_ins.
ignore_node(xn)
flag_match_found
end
def process_node_hyperlink(xn)
# hyperlink -> Pull
pull_node(xn)
add_warning(xn, "Found #{ xn.name_and_class }")
flag_match_found
end
def process_node_ins(xn)
# Change tracking: Insertion. Pull this node.
# See process_node_del
pull_node(xn)
flag_match_found
end
def process_node_lastrenderedpagebreak(xn)
# lastRenderedPageBreak
ignore_node(xn)
flag_match_found
end
def process_node_nobreakhyphen(xn)
# TODO: How to handle noBreakHyphen
# noBreakHyphen -> ?
ignore_node(xn)
flag_match_found
end
def process_node_p(xn)
# Paragraph
l = { :line => xn.line }
p_style = xn.at_xpath('./w:pPr/w:pStyle')
p_style_id = p_style ? p_style['w:val'] : nil
case p_style_id
when *paragraph_style_mappings.keys
# A known paragraph style that we have a mapping for
type, value, attr, options = paragraph_style_mappings[p_style_id]
root = @ke_context.get('root', xn)
return false if !root
para_ke = ElementRt.new(
type,
value,
attr,
if options.respond_to?(:call)
{ :location => l }.merge(options.call(xn))
else
{ :location => l }.merge(options || {})
end
)
root.add_child(para_ke)
@ke_context.set('p', para_ke)
@ke_context.with_text_container_stack(para_ke) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
# Hook to add specialized behavior in subclasses
process_node_p_additions(xn, para_ke)
@xn_context.process_children = false
else
raise(InvalidElementException, "Unhandled p_style_id #{ p_style_id.inspect }")
end
flag_match_found
end
def process_node_prooferr(xn)
# proofErr (Word proofing error)
ignore_node(xn)
flag_match_found
end
def process_node_ppr(xn)
# pPr (paragraph properties)
ignore_node(xn)
flag_match_found
end
def process_node_r(xn)
# Text run
trfas = TextRunFormatAttrs.new(xn)
case trfas.applied_attrs
when []
# no attributes applied, pull node
pull_node(xn)
when [:italic]
# italic with no other attributes -> markdown italics (*text*)
em_el = Kramdown::ElementRt.new(:em)
@ke_context.get_current_text_container(xn).add_child(em_el)
@ke_context.with_text_container_stack(em_el) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
@xn_context.process_children = false
when [:bold]
# bold with no other attributes -> markdown strong (**text**)
strong_el = Kramdown::ElementRt.new(:strong)
@ke_context.get_current_text_container(xn).add_child(strong_el)
@ke_context.with_text_container_stack(strong_el) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
@xn_context.process_children = false
else
# em with classes added for each applied attribute
em_el = Kramdown::ElementRt.new(:em, nil, { 'class' => trfas.applied_attrs.sort.join(' ') })
@ke_context.get_current_text_container(xn).add_child(em_el)
@ke_context.with_text_container_stack(em_el) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
@xn_context.process_children = false
end
flag_match_found
end
def process_node_rpr(xn)
# rPr (text_run properties)
ignore_node(xn)
flag_match_found
end
def process_node_sectpr(xn)
# sectPr
ignore_node(xn)
flag_match_found
end
def process_node_smarttag(xn)
# smartTag -> Pull
pull_node(xn)
add_warning(xn, "Found #{ xn.name_and_class }")
flag_match_found
end
def process_node_softhyphen(xn)
# softHyphen -> Ignore, raise warning
# Ignore for now, print a warning. There have been cases in the past
# where translators intended to use a hyphen, however it ended up as a
# softHyphen. Ignoring them would not be the expected behaviour.
# Let's see how often it occurs.
ignore_node(xn)
add_warning(xn, "Found #{ xn.name_and_class }")
flag_match_found
end
def process_node_t(xn)
# This is a DOCX Text node, pull it and use the contained Nokogiri text node
pull_node(xn)
flag_match_found
end
def process_node_text(xn)
# This is a Nokogiri text node
@ke_context.add_text_to_current_text_container(xn.text, xn)
flag_match_found
end
def process_node_tab(xn)
# tab
@ke_context.add_text_to_current_text_container("\t", xn)
flag_match_found
end
# ***********************************************************
# xml node processing helper methods
# ***********************************************************
# Capitalizes each word in string:
# 'this IS a string to CAPITALIZE' => 'This Is A String To Capitalize'
# @param [String] a_string
def capitalize_each_word_in_string(a_string)
a_string.split.map { |e| e.capitalize }.join(' ')
end
# Delete xn, send to deleted_text, children won't be processed
# @param [Nokogiri::XML::Node] xn
# @param [Boolean] send_to_deleted_text whether to send node's text to deleted_text
# @param [Boolean] send_to_notes whether to send node's text to notes
def delete_node(xn, send_to_deleted_text, send_to_notes)
@xn_context.process_children = false
add_deleted_text(xn, xn.text) if send_to_deleted_text
add_notes(xn, "Deleted text: #{ xn.text }") if send_to_notes
end
# Call this from xn processing methods where we want to record that a match
# has been found. This is used so that we can raise a warning for any
# unhandled XML nodes.
def flag_match_found
@xn_context.match_found = true
end
# Ignore xn, don't send to deleted_text, children won't be processed
# @param [Nokogiri::XML::Node] xn
def ignore_node(xn)
@xn_context.process_children = false
end
# Lowercases text contents of xn: 'TestString ALLCAPS' => 'teststrings allcaps'
# @param [Nokogiri::XML::Node] xn
def lowercase_node_text_contents!(xn)
xn.children.each { |xnc|
if xnc.text?
xnc.content = xnc.content.unicode_downcase
else
add_warning(
xn,
"lowercase_node_text_contents was called on node that contained non-text children: #{ xn.name_and_class }"
)
end
}
end
# Pull xn, Replacing self with children. Xml tree recursion will process children.
# @param [Nokogiri::XML::Node] xn
def pull_node(xn)
# nothing to do with node
end
# Deletes a_string from xn and all its descendant nodes.
# @param [String, Regexp] search_string_or_regex a string or regex for finding
# @param [String] replace_string the replacement string
# @param [Nokogiri::XML::Node] xn
def replace_string_inside_node!(search_string_or_regex, replace_string, xn)
if xn.text? && '' != xn.text && !xn.text.nil?
xn.content = xn.text.gsub(search_string_or_regex, replace_string)
else
xn.children.each { |child_xn|
replace_string_inside_node!(search_string_or_regex, replace_string, child_xn)
}
end
end
# Raises a warning and returns false if xn contains any text content other
# than whitespace.
# @param [Nokogiri::XML::Node] xn
def verify_only_whitespace_is_present(xn)
verify_text_matches_regex(xn, /\A[ \n]*\z/, 'contained non-whitespace')
end
def verify_text_matches_regex(xn, regex, warning_text)
t = xn.text.strip
if(t =~ regex)
true
else
add_warning(
xn,
"#{ xn.name_and_class } #{ warning_text }: #{ t.inspect }"
)
false
end
end
# Delegate instance method to class method
def paragraph_style_mappings
self.class.paragraph_style_mappings
end
# Hook for specialized behavior in sub classes.
# @param xn [Nokogiri::XmlNode] the p XML node
# @param ke [Kramdown::Element] the p kramdown element
def process_node_p_additions(xn, ke)
# Nothing to do. Override this method in specialized subclasses.
end
# Recursively post processes tree under ke.
# Hook for specialized behavior in sub classes.
# @param [Kramdown::Element] ke
def recursively_post_process_tree!(ke)
# Nothing to do
end
end
end
end
DOCX: Added `omath` node to handled docx nodes.
# TODO: Add .first_par class to first paragraph
require 'kramdown/document'
module Kramdown
module Parser
# Parses DOCX XML string to kramdown AT
#
# Naming conventions
#
# * node: refers to a Nokogiri::XML::Node (XML space)
# * element: refers to a Kramdown::Element (kramdown space). Note that we actually
# use a sub-class named Kramdown::ElementRt
# * ke: l_var that refers to a kramdown element
# * xn: l_var that refers to an XML node
class Docx
include Kramdown::AdjacentElementMerger
include Kramdown::ImportWhitespaceSanitizer
include Kramdown::NestedEmsProcessor
include Kramdown::TreeCleaner
include Kramdown::WhitespaceOutPusher
# Custom error
class InvalidElementException < RuntimeError; end
# Represents a TextRunFormat's attributes.
# @attr_reader bold [Boolean]
# @attr_reader italic [Boolean]
# @attr_reader smcaps [Boolean]
# @attr_reader subscript [Boolean]
# @attr_reader superscript [Boolean]
# @attr_reader underline [Boolean]
class TextRunFormatAttrs
SUPPORTED_TEXT_RUN_FORMAT_ATTRS = %i[
bold
italic
smcaps
subscript
superscript
underline
].sort
attr_reader *SUPPORTED_TEXT_RUN_FORMAT_ATTRS
# @param text_run [Nokogiri::XML::Node] the text_run's XML node
def initialize(text_run)
tr_style = text_run.at_xpath('./w:rPr')
if tr_style
# NOTE: w:b, w:i, and w:smallCaps are supposed to be a toggle properties
# (<w:b/>), however in some DOCX documents (ODT -> DOC -> DOCX), they
# have an unexpected `val` attribute that we need to check
# (<w:b w:val="false"/>). They could also be set to '0' if saved from MS Word.
@bold = (xn = tr_style.at_xpath('./w:b')) && !%w[false 0].include?(xn['w:val'])
@italic = (xn = tr_style.at_xpath('./w:i')) && !%w[false 0].include?(xn['w:val'])
@smcaps = (xn = tr_style.at_xpath('./w:smallCaps')) && !%w[false 0].include?(xn['w:val'])
@subscript = tr_style.at_xpath("./w:vertAlign[@w:val='subscript']")
@superscript = tr_style.at_xpath("./w:vertAlign[@w:val='superscript']")
@underline = (xn = tr_style.at_xpath('./w:u')) && 'none' != xn['w:val'] # val 'none' turns off underline
end
end
# Returns an array with symbols of all applied attributes, sorted
# alphabetically
def applied_attrs
@applied_attrs ||= SUPPORTED_TEXT_RUN_FORMAT_ATTRS.find_all { |e|
self.send(e)
}
end
end
# The hash with the parsing options.
attr_reader :options
# The array with the parser warnings.
attr_reader :warnings
# The original source string.
attr_reader :source
# The root element of element tree that is created from the source string.
attr_reader :root
# Maps DOCX paragraph style ids to kramdown elements
# @return [Hash] Hash with paragraph style ids as keys and arrays with the
# following items as values:
# * element type: a supported Kramdown::Element type
# * element value: String or nil
# * element attr: Hash or nil.
# * element options (can contain a lambda for lazy execution, gets passed the para XML node)
def self.paragraph_style_mappings
{
"header1" => [:header, nil, { } , lambda { |para| {:level => 1, :raw_text => para.text} }],
"header2" => [:header, nil, { } , lambda { |para| {:level => 2, :raw_text => para.text} }],
"header3" => [:header, nil, { } , lambda { |para| {:level => 3, :raw_text => para.text} }],
"normal" => [:p , nil, {'class' => 'normal'} , nil],
"paraTest" => [:p , nil, {'class' => 'para_test'} , nil],
"horizontalRule" => [:hr , nil, { } , nil],
}
end
# Parse the +source+ string into an element tree, possibly using the parsing +options+, and
# return the root element of the element tree and an array with warning messages.
# @param source [String] contents of word/document.xml as string
# @param options [Hash, optional] these will be passed to Kramdown::Parser instance
def self.parse(source, options = {})
parser = new(source, options)
parser.parse
[parser.root, parser.warnings]
end
# @note We change the default kramdown parser behavior where you can't
# just create a parser instance. This makes it easier to use this parser
# for validation purpose, and to tie it into our workflows.
#
# @param source [String] contents of word/document.xml as string
# @param options [Hash, optional] these will be passed to Kramdown::Parser
def initialize(source, options)
@source = source
@options = {
:line_width => 100000, # set to very large value so that each para is on a single line
:input => 'KramdownRepositext' # that is what we generate as string below
}.merge(options)
@root = nil
@warnings = []
end
# Parses @source into a Kramdown tree under @root.
def parse
@root = Kramdown::ElementRt.new(
:root, nil, nil, :encoding => 'UTF-8', :location => { :line => 1 }
)
@ke_context = Folio::KeContext.new({ 'root' => @root }, self)
# Transform the XML tree
xml_document = Nokogiri::XML(@source) { |config| config.noblanks }
body_xn = xml_document.at_xpath('//w:document//w:body')
body_xn.children.each do |child_xn|
process_xml_node(child_xn)
end
post_process_kramdown_tree!(@ke_context.get('root', nil))
end
# @param [Nokogiri::XML::Node] xn the XML Node to process
# @param [String] message
def add_warning(xn, message)
if '' != message.to_s
@warnings << {
message: message,
line: xn.line,
path: xn.name_and_class_path
}
end
end
private
# Processes an xml_node
# @param xn [Nokogiri::XML::Node] the XML Node to process
def process_xml_node(xn)
raise(InvalidElementException, "xn cannot be nil") if xn.nil?
# TODO: Don't use OpenStruct here for performance reasons.
@xn_context = OpenStruct.new(
:match_found => false,
:process_children => true,
)
if xn.duplicate_of?(xn.parent)
# xn is duplicate of its parent, pull it
pull_node(xn)
@xn_context.match_found = true
else
method_name = "process_node_#{ xn.name.downcase.gsub('-', '_') }"
if respond_to?(method_name, true)
self.send(method_name, xn)
else
raise InvalidElementException.new(
"Unexpected element type #{ xn.name } on line #{ xn.line }. Requires method #{ method_name.inspect }."
)
end
end
if !@xn_context.match_found
add_warning(xn, "Unhandled XML node #{ xn.name_and_class }")
end
# recurse over child XML Nodes
if @xn_context.process_children
xn.children.each { |xnc| process_xml_node(xnc) }
end
end
# Modifies kramdown_tree in place.
# NOTE: this method has potential for optimization. We blindly run
# recursively_merge_adjacent_elements in a number of places. This is only
# necessary if the previous methods actually modified the tree.
# I'm thinking only if nodes were removed, however that needs to be
# confirmed.
# @param kramdown_tree [Kramdown::Element] the root of the tree
def post_process_kramdown_tree!(kramdown_tree)
# override this to post process elements in the kramdown tree
# NOTE: It's important to call the methods below for correct results.
# You have two options:
# 1. call super if you override this method
# 2. copy the methods below into your own method if you need different sequence
recursively_merge_adjacent_elements!(kramdown_tree)
recursively_clean_up_nested_ems!(kramdown_tree) # has to be called after process_temp_em_class
recursively_push_out_whitespace!(kramdown_tree)
# needs to run after whitespace has been pushed out so that we won't
# have a leading \t inside an :em that is the first child in a para.
# After whitespace is pushed out, the \t will be a direct :text child
# of :p and first char will be easy to detect.
recursively_sanitize_whitespace_during_import!(kramdown_tree)
# merge again since we may have new identical siblings after all the
# other processing.
recursively_merge_adjacent_elements!(kramdown_tree)
recursively_clean_up_tree!(kramdown_tree)
# Run this again since we may have new locations with leading or trailing whitespace
recursively_sanitize_whitespace_during_import!(kramdown_tree)
# merge again since we may have new identical siblings after cleaning up the tree
# e.g. an italic span with whitespace only between two text nodes was removed.
recursively_merge_adjacent_elements!(kramdown_tree)
# DOCX import specific cleanup
recursively_post_process_tree!(kramdown_tree)
end
# ***********************************************
# Node type specific processors
# ***********************************************
def process_node_bookmarkend(xn)
# bookmarkEnd
ignore_node(xn)
flag_match_found
end
def process_node_bookmarkstart(xn)
# bookmarkStart
ignore_node(xn)
flag_match_found
end
def process_node_commentrangestart(xn)
# commentRangeStart
ignore_node(xn)
flag_match_found
end
def process_node_commentrangeend(xn)
# commentRangeEnd
ignore_node(xn)
flag_match_found
end
def process_node_commentreference(xn)
# commentReference
ignore_node(xn)
flag_match_found
end
def process_node_del(xn)
# Change tracking: Deletion. Ignore this node.
# See process_node_ins.
ignore_node(xn)
flag_match_found
end
def process_node_hyperlink(xn)
# hyperlink -> Pull
pull_node(xn)
add_warning(xn, "Found #{ xn.name_and_class }")
flag_match_found
end
def process_node_ins(xn)
# Change tracking: Insertion. Pull this node.
# See process_node_del
pull_node(xn)
flag_match_found
end
def process_node_lastrenderedpagebreak(xn)
# lastRenderedPageBreak
ignore_node(xn)
flag_match_found
end
def process_node_nobreakhyphen(xn)
# TODO: How to handle noBreakHyphen
# noBreakHyphen -> ?
ignore_node(xn)
flag_match_found
end
def process_node_omath(xn)
# TODO: How to handle omath
ignore_node(xn)
flag_match_found
end
def process_node_p(xn)
# Paragraph
l = { :line => xn.line }
p_style = xn.at_xpath('./w:pPr/w:pStyle')
p_style_id = p_style ? p_style['w:val'] : nil
case p_style_id
when *paragraph_style_mappings.keys
# A known paragraph style that we have a mapping for
type, value, attr, options = paragraph_style_mappings[p_style_id]
root = @ke_context.get('root', xn)
return false if !root
para_ke = ElementRt.new(
type,
value,
attr,
if options.respond_to?(:call)
{ :location => l }.merge(options.call(xn))
else
{ :location => l }.merge(options || {})
end
)
root.add_child(para_ke)
@ke_context.set('p', para_ke)
@ke_context.with_text_container_stack(para_ke) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
# Hook to add specialized behavior in subclasses
process_node_p_additions(xn, para_ke)
@xn_context.process_children = false
else
raise(InvalidElementException, "Unhandled p_style_id #{ p_style_id.inspect }")
end
flag_match_found
end
def process_node_prooferr(xn)
# proofErr (Word proofing error)
ignore_node(xn)
flag_match_found
end
def process_node_ppr(xn)
# pPr (paragraph properties)
ignore_node(xn)
flag_match_found
end
def process_node_r(xn)
# Text run
trfas = TextRunFormatAttrs.new(xn)
case trfas.applied_attrs
when []
# no attributes applied, pull node
pull_node(xn)
when [:italic]
# italic with no other attributes -> markdown italics (*text*)
em_el = Kramdown::ElementRt.new(:em)
@ke_context.get_current_text_container(xn).add_child(em_el)
@ke_context.with_text_container_stack(em_el) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
@xn_context.process_children = false
when [:bold]
# bold with no other attributes -> markdown strong (**text**)
strong_el = Kramdown::ElementRt.new(:strong)
@ke_context.get_current_text_container(xn).add_child(strong_el)
@ke_context.with_text_container_stack(strong_el) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
@xn_context.process_children = false
else
# em with classes added for each applied attribute
em_el = Kramdown::ElementRt.new(:em, nil, { 'class' => trfas.applied_attrs.sort.join(' ') })
@ke_context.get_current_text_container(xn).add_child(em_el)
@ke_context.with_text_container_stack(em_el) do
xn.children.each { |xnc| process_xml_node(xnc) }
end
@xn_context.process_children = false
end
flag_match_found
end
def process_node_rpr(xn)
# rPr (text_run properties)
ignore_node(xn)
flag_match_found
end
def process_node_sectpr(xn)
# sectPr
ignore_node(xn)
flag_match_found
end
def process_node_smarttag(xn)
# smartTag -> Pull
pull_node(xn)
add_warning(xn, "Found #{ xn.name_and_class }")
flag_match_found
end
def process_node_softhyphen(xn)
# softHyphen -> Ignore, raise warning
# Ignore for now, print a warning. There have been cases in the past
# where translators intended to use a hyphen, however it ended up as a
# softHyphen. Ignoring them would not be the expected behaviour.
# Let's see how often it occurs.
ignore_node(xn)
add_warning(xn, "Found #{ xn.name_and_class }")
flag_match_found
end
def process_node_t(xn)
# This is a DOCX Text node, pull it and use the contained Nokogiri text node
pull_node(xn)
flag_match_found
end
def process_node_text(xn)
# This is a Nokogiri text node
@ke_context.add_text_to_current_text_container(xn.text, xn)
flag_match_found
end
def process_node_tab(xn)
# tab
@ke_context.add_text_to_current_text_container("\t", xn)
flag_match_found
end
# ***********************************************************
# xml node processing helper methods
# ***********************************************************
# Capitalizes each word in string:
# 'this IS a string to CAPITALIZE' => 'This Is A String To Capitalize'
# @param [String] a_string
def capitalize_each_word_in_string(a_string)
a_string.split.map { |e| e.capitalize }.join(' ')
end
# Delete xn, send to deleted_text, children won't be processed
# @param [Nokogiri::XML::Node] xn
# @param [Boolean] send_to_deleted_text whether to send node's text to deleted_text
# @param [Boolean] send_to_notes whether to send node's text to notes
def delete_node(xn, send_to_deleted_text, send_to_notes)
@xn_context.process_children = false
add_deleted_text(xn, xn.text) if send_to_deleted_text
add_notes(xn, "Deleted text: #{ xn.text }") if send_to_notes
end
# Call this from xn processing methods where we want to record that a match
# has been found. This is used so that we can raise a warning for any
# unhandled XML nodes.
def flag_match_found
@xn_context.match_found = true
end
# Ignore xn, don't send to deleted_text, children won't be processed
# @param [Nokogiri::XML::Node] xn
def ignore_node(xn)
@xn_context.process_children = false
end
# Lowercases text contents of xn: 'TestString ALLCAPS' => 'teststrings allcaps'
# @param [Nokogiri::XML::Node] xn
def lowercase_node_text_contents!(xn)
xn.children.each { |xnc|
if xnc.text?
xnc.content = xnc.content.unicode_downcase
else
add_warning(
xn,
"lowercase_node_text_contents was called on node that contained non-text children: #{ xn.name_and_class }"
)
end
}
end
# Pull xn, Replacing self with children. Xml tree recursion will process children.
# @param [Nokogiri::XML::Node] xn
def pull_node(xn)
# nothing to do with node
end
# Deletes a_string from xn and all its descendant nodes.
# @param [String, Regexp] search_string_or_regex a string or regex for finding
# @param [String] replace_string the replacement string
# @param [Nokogiri::XML::Node] xn
def replace_string_inside_node!(search_string_or_regex, replace_string, xn)
if xn.text? && '' != xn.text && !xn.text.nil?
xn.content = xn.text.gsub(search_string_or_regex, replace_string)
else
xn.children.each { |child_xn|
replace_string_inside_node!(search_string_or_regex, replace_string, child_xn)
}
end
end
# Raises a warning and returns false if xn contains any text content other
# than whitespace.
# @param [Nokogiri::XML::Node] xn
def verify_only_whitespace_is_present(xn)
verify_text_matches_regex(xn, /\A[ \n]*\z/, 'contained non-whitespace')
end
def verify_text_matches_regex(xn, regex, warning_text)
t = xn.text.strip
if(t =~ regex)
true
else
add_warning(
xn,
"#{ xn.name_and_class } #{ warning_text }: #{ t.inspect }"
)
false
end
end
# Delegate instance method to class method
def paragraph_style_mappings
self.class.paragraph_style_mappings
end
# Hook for specialized behavior in sub classes.
# @param xn [Nokogiri::XmlNode] the p XML node
# @param ke [Kramdown::Element] the p kramdown element
def process_node_p_additions(xn, ke)
# Nothing to do. Override this method in specialized subclasses.
end
# Recursively post processes tree under ke.
# Hook for specialized behavior in sub classes.
# @param [Kramdown::Element] ke
def recursively_post_process_tree!(ke)
# Nothing to do
end
end
end
end
|
module Lita
module Handlers
class Nagios < Handler
def self.default_config(config)
config.default_room = nil
config.cgi = nil
config.user = nil
config.pass = nil
config.version = 3
config.time_format = "iso8601"
config.verify_ssl = true
end
def initialize(robot)
@site = NagiosHarder::Site.new(
config.cgi,
config.user,
config.pass,
config.version,
config.time_format,
config.verify_ssl
)
super(robot)
end
##
# Chat routes
##
route /^nagios\s+(?<action>enable|disable)\s+notif(ication(s)?)?/, :toggle_notifications,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" }
},
help: {
"nagios enable notif(ication(s)) <-h | --host HOST> [-s | --service SERVICE]" => "Enable notifications for given host/service",
"nagios disable notif(ication(s)) <-h | --host HOST> [-s | --service SERVICE]" => "Disable notifications for given host/service",
}
def toggle_notifications(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
action = response.match_data[:action]
reply = @site.send("#{action}_service_notifications", args[:host], args[:service])
response.reply(reply)
end
route /^nagios\s+recheck/, :recheck,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" }
},
help: {
"nagios recheck <-h | --host HOST> [-s | --service SERVICE]" => "Reschedule check for given host/service"
}
def recheck(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
if args[:service]
method_w_params = [ :schedule_service_check, args[:host], args[:service] ]
reply = "#{args[:service]} on #{args[:host]}"
else
method_w_params = [ :schedule_host_check, args[:host] ]
reply = args[:host]
end
reply = @site.send(*method_w_params) ? "Check scheduled for #{reply}" : "Failed to schedule check for #{reply}"
response.reply(reply)
end
route /^nagios\s+ack(nowledge)?/, :acknowledge,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" },
message: { short: "m" }
},
help: {
"nagios ack(nowledge) <-h | --host HOST> [-s | --service SERVICE] [-m | --message MESSAGE]" => "Acknowledge host/service problem with optional message",
}
def acknowledge(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
user = response.message.source.user.name
message = args[:message] ? "#{args[:message]} (#{user})" : "acked by #{user}"
if args[:service]
method_w_params = [ :acknowledge_service, args[:host], args[:service], message ]
reply = "#{args[:service]} on #{args[:host]}"
else
method_w_params = [ :acknowledge_host, args[:host], message ]
reply = args[:host]
end
reply = @site.send(*method_w_params) ? "Acknowledgment set for #{reply}" : "Failed to acknowledge #{reply}"
response.reply(reply)
end
route /^nagios(\s+(?<type>fixed|flexible))?\s+downtime/, :schedule_downtime,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" },
duration: { short: "d" }
},
help: {
"nagios (fixed|flexible) downtime <-d | --duration DURATION > <-h | --host HOST> [-s | --service SERVICE]" => "Schedule downtime for a host/service with duration units in (m, h, d, default to seconds)"
}
def schedule_downtime(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
units = { "m" => :minutes, "h" => :hours, "d" => :days }
match = /^(?<value>\d+)(?<unit>[#{units.keys.join}])?$/.match(args[:duration])
return response.reply("Invalid downtime duration") unless (match and match[:value])
duration = match[:unit] ? match[:value].to_i.send(units[match[:unit]]) : match[:value].to_i
options = case response.match_data[:type]
when "fixed"
{ type: :fixed, start_time: Time.now, end_time: Time.now + duration }
when "flexible"
{ type: :flexible, hours: (duration / 3600), minutes: (duration % 3600 / 60) }
end.merge({ author: "#{response.message.source.user.name} via Lita" })
if args[:service]
method_w_params = [ :schedule_service_downtime, args[:host], args[:service], options ]
reply = "#{args[:service]} on #{args[:host]}"
else
method_w_params = [ :schedule_host_downtime, args[:host], options ]
reply = args[:host]
end
reply = @site.send(*method_w_params) ? "#{options[:type].capitalize} downtime set for #{reply}" : "Failed to schedule downtime for #{reply}"
response.reply(reply)
end
##
# HTTP endpoints
##
http.post "/nagios/notifications", :receive
def receive(request, response)
if request.params.has_key?("type")
notif_type = request.params["type"].to_sym
unless respond_to?(notif_type, true)
raise "'#{notif_type}' is not supported by Nagios handler"
end
else
raise "Notification type must be defined in Nagios command"
end
if request.params.has_key?("room")
room = request.params["room"]
elsif config.default_room
room = config.default_room
else
raise "Room must be defined. Either fix your command or specify a default room ('config.handlers.nagios.default_room')"
end
message = send(notif_type, request.params)
target = Source.new(room: room)
robot.send_message(target, "nagios: #{message}")
rescue Exception => e
Lita.logger.error(e)
end
private
def host(params)
case params["state"]
when "UP"
color = :light_green
when "DOWN"
color = :light_red
when "UNREACHABLE"
color = :orange
end
status = params["state"]
message = "#{params["host"]} is #{status}: #{params["output"]}"
end
def service(params)
case params["state"]
when "OK"
color = :light_green
when "WARNING"
color = :yellow
when "CRITICAL"
color = :light_red
when "UNKNOWN"
color = :orange
end
status = params["state"]
message = "#{params["host"]}:#{params["description"]} is #{status}: #{params["output"]}"
end
end
Lita.register_handler(Nagios)
end
end
handle only problem, recovery and ack. remove dummy color support
module Lita
module Handlers
class Nagios < Handler
def self.default_config(config)
config.default_room = nil
config.cgi = nil
config.user = nil
config.pass = nil
config.version = 3
config.time_format = "iso8601"
config.verify_ssl = true
end
def initialize(robot)
@site = NagiosHarder::Site.new(
config.cgi,
config.user,
config.pass,
config.version,
config.time_format,
config.verify_ssl
)
super(robot)
end
##
# Chat routes
##
route /^nagios\s+(?<action>enable|disable)\s+notif(ication(s)?)?/, :toggle_notifications,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" }
},
help: {
"nagios enable notif(ication(s)) <-h | --host HOST> [-s | --service SERVICE]" => "Enable notifications for given host/service",
"nagios disable notif(ication(s)) <-h | --host HOST> [-s | --service SERVICE]" => "Disable notifications for given host/service",
}
def toggle_notifications(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
action = response.match_data[:action]
reply = @site.send("#{action}_service_notifications", args[:host], args[:service])
response.reply(reply)
end
route /^nagios\s+recheck/, :recheck,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" }
},
help: {
"nagios recheck <-h | --host HOST> [-s | --service SERVICE]" => "Reschedule check for given host/service"
}
def recheck(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
if args[:service]
method_w_params = [ :schedule_service_check, args[:host], args[:service] ]
reply = "#{args[:service]} on #{args[:host]}"
else
method_w_params = [ :schedule_host_check, args[:host] ]
reply = args[:host]
end
reply = @site.send(*method_w_params) ? "Check scheduled for #{reply}" : "Failed to schedule check for #{reply}"
response.reply(reply)
end
route /^nagios\s+ack(nowledge)?/, :acknowledge,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" },
message: { short: "m" }
},
help: {
"nagios ack(nowledge) <-h | --host HOST> [-s | --service SERVICE] [-m | --message MESSAGE]" => "Acknowledge host/service problem with optional message",
}
def acknowledge(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
user = response.message.source.user.name
message = args[:message] ? "#{args[:message]} (#{user})" : "acked by #{user}"
if args[:service]
method_w_params = [ :acknowledge_service, args[:host], args[:service], message ]
reply = "#{args[:service]} on #{args[:host]}"
else
method_w_params = [ :acknowledge_host, args[:host], message ]
reply = args[:host]
end
reply = @site.send(*method_w_params) ? "Acknowledgment set for #{reply}" : "Failed to acknowledge #{reply}"
response.reply(reply)
end
route /^nagios(\s+(?<type>fixed|flexible))?\s+downtime/, :schedule_downtime,
command: true,
restrict_to: ["admins"],
kwargs: {
host: { short: "h" },
service: { short: "s" },
duration: { short: "d" }
},
help: {
"nagios (fixed|flexible) downtime <-d | --duration DURATION > <-h | --host HOST> [-s | --service SERVICE]" => "Schedule downtime for a host/service with duration units in (m, h, d, default to seconds)"
}
def schedule_downtime(response)
args = response.extensions[:kwargs]
return response.reply("Missing 'host' argument") unless args[:host]
units = { "m" => :minutes, "h" => :hours, "d" => :days }
match = /^(?<value>\d+)(?<unit>[#{units.keys.join}])?$/.match(args[:duration])
return response.reply("Invalid downtime duration") unless (match and match[:value])
duration = match[:unit] ? match[:value].to_i.send(units[match[:unit]]) : match[:value].to_i
options = case response.match_data[:type]
when "fixed"
{ type: :fixed, start_time: Time.now, end_time: Time.now + duration }
when "flexible"
{ type: :flexible, hours: (duration / 3600), minutes: (duration % 3600 / 60) }
end.merge({ author: "#{response.message.source.user.name} via Lita" })
if args[:service]
method_w_params = [ :schedule_service_downtime, args[:host], args[:service], options ]
reply = "#{args[:service]} on #{args[:host]}"
else
method_w_params = [ :schedule_host_downtime, args[:host], options ]
reply = args[:host]
end
reply = @site.send(*method_w_params) ? "#{options[:type].capitalize} downtime set for #{reply}" : "Failed to schedule downtime for #{reply}"
response.reply(reply)
end
##
# HTTP endpoints
##
http.post "/nagios/notifications", :receive
def receive(request, response)
params = request.params
if params.has_key?("room")
room = params["room"]
elsif config.default_room
room = config.default_room
else
raise "Room must be defined. Either fix your command or specify a default room ('config.handlers.nagios.default_room')"
end
message = nil
case params["notificationtype"]
when "ACKNOWLEDGEMENT"
message = "[ACK] "
when "PROBLEM", "RECOVERY"
message = ""
else
# Don't process FLAPPING* and DOWNTIME* events for now
return
end
case params["type"]
when "service"
message += "#{params["host"]}:#{params["description"]} is #{params["state"]}: #{params["output"]}"
when "host"
message += "#{params["host"]} is #{params["state"]}: #{params["output"]}"
else
raise "Notification type must be defined in Nagios command ('host' or 'service')"
end
target = Source.new(room: room)
robot.send_message(target, "nagios: #{message}")
rescue Exception => e
Lita.logger.error(e)
end
end
Lita.register_handler(Nagios)
end
end
|
require 'lita-keyword-arguments'
##
# Lita module.
#
module Lita
##
# Lita handlers module.
#
module Handlers
##
# Generator of random numbers and strings for the Lita chat bot.
#
class Random < Handler # rubocop:disable Metrics/ClassLength
HELP = {
'random' =>
'random float number, greater or equal to 0 and lesser than 1',
'random <to>' =>
'random integer or float number, ' \
'greater or equal to 0 and lesser than `to`',
'random <from> <to>' =>
'random integer or float number, ' \
'greater or equal to `from` and lesser than `to`',
'random case <s>' =>
'randomize case of each character of string `s`',
'random base64 <n=16>' =>
'random base64 string, length of source string is n, ' \
'length of result is about `n * 4 / 3` ' \
'(24 with default value of `n`)',
'random hex <n=16>' =>
'random hexadecimal string with length `n * 2`',
'random uuid' =>
'v4 random UUID (Universally Unique IDentifier). ' \
'The version 4 UUID is purely random (except the version). ' \
'It doesn’t contain meaningful information ' \
'such as MAC address, time, etc.',
'random password <n=16>' =>
'random password with length `n` containing characters ' \
'in upper and lower case, and digits',
'random smart password <n=8>' =>
'random pronounceable password with a minimum length of `n`',
'shuffle <array, ...>' =>
'new array with elements of `array` shuffled',
'sample <n=1> <array, ...>' =>
'choose `n` random elements from `array`',
}
route(
/^rand(om)?((\s+(?<from>\d+(\.\d+)?))?\s+(?<to>\d+(\.\d+)?))?($|\s+)/i,
:route_random,
command: true, help: HELP,
kwargs: {
from: { short: 'f' },
to: { short: 't' },
}
)
def route_random(response)
from = extract_argument(response, 0, :from, &method(:str_to_num)) || 0
to = extract_argument(response, 1, :to, &method(:str_to_num)) || 1.0
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(::Random.rand(from...to).to_s)
end
route(/^rand(om)?\s*case(\s+(?<s>.*))?$/i,
:route_random_case, command: true)
def route_random_case(response)
response.reply(random_case(response.matches[0][0] || ''))
end
route(
/^rand(om)?\s*b(ase)?64(\s+(?<n>\d+))?($|\s+)/i,
:route_random_base64,
command: true,
kwargs: {
size: { short: 's' },
}
)
def route_random_base64(response)
size = extract_argument(response, 0, :size, &:to_i) || 16
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(SecureRandom.base64(size))
end
route(
/^rand(om)?\s*(he?)?x(\s+(?<n>\d+))?($|\s+)/i,
:route_random_hex,
command: true,
kwargs: {
size: { short: 's' },
}
)
def route_random_hex(response)
size = extract_argument(response, 0, :size, &:to_i) || 16
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(SecureRandom.hex(size))
end
route(/^rand(om)?\s*u?uid$/i, :route_random_uuid, command: true)
def route_random_uuid(response)
response.reply(SecureRandom.uuid)
end
route(
/^rand(om)?\s*smart\s*pass(word)?(\s+(?<n>\d+))?($|\s+)/i,
:route_random_smart_pass,
command: true,
kwargs: {
length: { short: 'l' },
}
)
def route_random_smart_pass(response)
length = extract_argument(response, 0, :length, &:to_i) || 8
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(smart_password(length))
end
route(/^rand(om)?\s*pass(word)?$/i, :route_random_pass, command: true)
def route_random_pass(response)
response.reply(password)
end
route(/^rand(om)?\s*pass(word)?\s+(?<n>\d+)$/i,
:route_random_pass_n, command: true)
def route_random_pass_n(response)
length = response.matches[0][0].to_i
response.reply(password(length))
end
route(/^shuffle(\s+(?<array>.*))?$/i, :route_shuffle, command: true)
def route_shuffle(response)
s = response.matches[0][0]
a = s ? s.split(',').map(&:strip) : []
response.reply(a.shuffle.join(', '))
end
route(/^sample(\s+((?<n>\d+)\s+)?(?<array>.*))?$/i,
:route_sample, command: true)
def route_sample(response)
matches = response.matches[0]
n = matches[0]
s = matches[1]
a = s ? s.split(',').map(&:strip) : []
result = n ? a.sample(n.to_i).join(', ') : a.sample.to_s
response.reply(result)
end
protected
def random_case(s)
s.each_char.map do |c|
::Random.rand(2).zero? ? c.upcase : c.downcase
end.join
end
SMART_PASS_SEQS = {
false => %w(
b c d f g h j k l m n p qu r s t v w x z
ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr lt
),
true => %w(a e i o u y),
}
def smart_password(min_length = 8)
password = ''
sequence_id = false
while password.length < min_length
sequence = SMART_PASS_SEQS[sequence_id]
password << sequence.sample
sequence_id = !sequence_id
end
password
end
PASS_CHARS = [*'a'..'z', *'A'..'Z', *'0'..'9']
def password(length = 16)
(0...length).map { |_| PASS_CHARS.sample }.join
end
private
def extract_argument(response, index, name)
matches = response.matches[0]
kwargs = response.extensions[:kwargs]
positional = matches[index]
kw = kwargs[name]
fail if positional && kw
s = positional || kw
block_given? && s ? yield(s) : s
end
def str_to_num(s)
s =~ /\./ ? s.to_f : s.to_i
end
end
Lita.register_handler(Random)
end
end
Implement keuword arguments for command "random password"
require 'lita-keyword-arguments'
##
# Lita module.
#
module Lita
##
# Lita handlers module.
#
module Handlers
##
# Generator of random numbers and strings for the Lita chat bot.
#
class Random < Handler # rubocop:disable Metrics/ClassLength
HELP = {
'random' =>
'random float number, greater or equal to 0 and lesser than 1',
'random <to>' =>
'random integer or float number, ' \
'greater or equal to 0 and lesser than `to`',
'random <from> <to>' =>
'random integer or float number, ' \
'greater or equal to `from` and lesser than `to`',
'random case <s>' =>
'randomize case of each character of string `s`',
'random base64 <n=16>' =>
'random base64 string, length of source string is n, ' \
'length of result is about `n * 4 / 3` ' \
'(24 with default value of `n`)',
'random hex <n=16>' =>
'random hexadecimal string with length `n * 2`',
'random uuid' =>
'v4 random UUID (Universally Unique IDentifier). ' \
'The version 4 UUID is purely random (except the version). ' \
'It doesn’t contain meaningful information ' \
'such as MAC address, time, etc.',
'random password <n=16>' =>
'random password with length `n` containing characters ' \
'in upper and lower case, and digits',
'random smart password <n=8>' =>
'random pronounceable password with a minimum length of `n`',
'shuffle <array, ...>' =>
'new array with elements of `array` shuffled',
'sample <n=1> <array, ...>' =>
'choose `n` random elements from `array`',
}
route(
/^rand(om)?((\s+(?<from>\d+(\.\d+)?))?\s+(?<to>\d+(\.\d+)?))?($|\s+)/i,
:route_random,
command: true, help: HELP,
kwargs: {
from: { short: 'f' },
to: { short: 't' },
}
)
def route_random(response)
from = extract_argument(response, 0, :from, &method(:str_to_num)) || 0
to = extract_argument(response, 1, :to, &method(:str_to_num)) || 1.0
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(::Random.rand(from...to).to_s)
end
route(/^rand(om)?\s*case(\s+(?<s>.*))?$/i,
:route_random_case, command: true)
def route_random_case(response)
response.reply(random_case(response.matches[0][0] || ''))
end
route(
/^rand(om)?\s*b(ase)?64(\s+(?<n>\d+))?($|\s+)/i,
:route_random_base64,
command: true,
kwargs: {
size: { short: 's' },
}
)
def route_random_base64(response)
size = extract_argument(response, 0, :size, &:to_i) || 16
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(SecureRandom.base64(size))
end
route(
/^rand(om)?\s*(he?)?x(\s+(?<n>\d+))?($|\s+)/i,
:route_random_hex,
command: true,
kwargs: {
size: { short: 's' },
}
)
def route_random_hex(response)
size = extract_argument(response, 0, :size, &:to_i) || 16
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(SecureRandom.hex(size))
end
route(/^rand(om)?\s*u?uid$/i, :route_random_uuid, command: true)
def route_random_uuid(response)
response.reply(SecureRandom.uuid)
end
route(
/^rand(om)?\s*smart\s*pass(word)?(\s+(?<n>\d+))?($|\s+)/i,
:route_random_smart_pass,
command: true,
kwargs: {
length: { short: 'l' },
}
)
def route_random_smart_pass(response)
length = extract_argument(response, 0, :length, &:to_i) || 8
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(smart_password(length))
end
route(
/^rand(om)?\s*pass(word)?(\s+(?<n>\d+))?($|\s+)/i,
:route_random_pass,
command: true,
kwargs: {
length: { short: 'l' },
}
)
def route_random_pass(response)
length = extract_argument(response, 0, :length, &:to_i) || 16
rescue RuntimeError # rubocop:disable Lint/HandleExceptions
else
response.reply(password(length))
end
route(/^shuffle(\s+(?<array>.*))?$/i, :route_shuffle, command: true)
def route_shuffle(response)
s = response.matches[0][0]
a = s ? s.split(',').map(&:strip) : []
response.reply(a.shuffle.join(', '))
end
route(/^sample(\s+((?<n>\d+)\s+)?(?<array>.*))?$/i,
:route_sample, command: true)
def route_sample(response)
matches = response.matches[0]
n = matches[0]
s = matches[1]
a = s ? s.split(',').map(&:strip) : []
result = n ? a.sample(n.to_i).join(', ') : a.sample.to_s
response.reply(result)
end
protected
def random_case(s)
s.each_char.map do |c|
::Random.rand(2).zero? ? c.upcase : c.downcase
end.join
end
SMART_PASS_SEQS = {
false => %w(
b c d f g h j k l m n p qu r s t v w x z
ch cr fr nd ng nk nt ph pr rd sh sl sp st th tr lt
),
true => %w(a e i o u y),
}
def smart_password(min_length = 8)
password = ''
sequence_id = false
while password.length < min_length
sequence = SMART_PASS_SEQS[sequence_id]
password << sequence.sample
sequence_id = !sequence_id
end
password
end
PASS_CHARS = [*'a'..'z', *'A'..'Z', *'0'..'9']
def password(length = 16)
(0...length).map { |_| PASS_CHARS.sample }.join
end
private
def extract_argument(response, index, name)
matches = response.matches[0]
kwargs = response.extensions[:kwargs]
positional = matches[index]
kw = kwargs[name]
fail if positional && kw
s = positional || kw
block_given? && s ? yield(s) : s
end
def str_to_num(s)
s =~ /\./ ? s.to_f : s.to_i
end
end
Lita.register_handler(Random)
end
end
|
class GlibNetworking < Formula
desc "Network related modules for glib"
homepage "https://launchpad.net/glib-networking"
url "https://download.gnome.org/sources/glib-networking/2.46/glib-networking-2.46.1.tar.xz"
sha256 "d5034214217f705891b6c9e719cc2c583c870bfcfdc454ebbb5e5e8940ac90b1"
bottle do
cellar :any
sha256 "3c1b629da76dcdb2f6525fe68849f63afc822e772b86170c1b9af84ad6c1df3d" => :el_capitan
sha256 "9912eeb2398fedbe1339ab96880af9925cefa8f9de43c6bc503fbc3e569b8d72" => :yosemite
sha256 "a1d967fe99e015e6463e2079a26cbe26405f531076dceebb95593f4530701c79" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "intltool" => :build
depends_on "gettext"
depends_on "glib"
depends_on "gnutls"
depends_on "gsettings-desktop-schemas"
link_overwrite "lib/gio/modules"
def install
# Install files to `lib` instead of `HOMEBREW_PREFIX/lib`.
inreplace "configure", "$($PKG_CONFIG --variable giomoduledir gio-2.0)", lib/"gio/modules"
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-ca-certificates=#{etc}/openssl/cert.pem",
# Remove when p11-kit >= 0.20.7 builds on OSX
# see https://github.com/Homebrew/homebrew/issues/36323
# and https://bugs.freedesktop.org/show_bug.cgi?id=91602
"--without-pkcs11"
system "make", "install"
# Delete the cache, will regenerate it in post_install
rm lib/"gio/modules/giomodule.cache"
end
def post_install
system Formula["glib"].opt_bin/"gio-querymodules", HOMEBREW_PREFIX/"lib/gio/modules"
end
test do
(testpath/"gtls-test.c").write <<-EOS.undent
#include <gio/gio.h>
int main (int argc, char *argv[])
{
if (g_tls_backend_supports_tls (g_tls_backend_get_default()))
return 0;
else
return 1;
}
EOS
# From `pkg-config --cflags --libs gio-2.0`
flags = [
"-D_REENTRANT",
"-I#{HOMEBREW_PREFIX}/include/glib-2.0",
"-I#{HOMEBREW_PREFIX}/lib/glib-2.0/include",
"-I#{HOMEBREW_PREFIX}/opt/gettext/include",
"-L#{HOMEBREW_PREFIX}/lib",
"-L#{HOMEBREW_PREFIX}/opt/gettext/lib",
"-lgio-2.0", "-lgobject-2.0", "-lglib-2.0", "-lintl",
]
system ENV.cc, "gtls-test.c", "-o", "gtls-test", *flags
system "./gtls-test"
end
end
glib-networking: update 2.46.1 bottle.
class GlibNetworking < Formula
desc "Network related modules for glib"
homepage "https://launchpad.net/glib-networking"
url "https://download.gnome.org/sources/glib-networking/2.46/glib-networking-2.46.1.tar.xz"
sha256 "d5034214217f705891b6c9e719cc2c583c870bfcfdc454ebbb5e5e8940ac90b1"
bottle do
cellar :any
sha256 "019a74e4cf9d8479d2379ac3d2833150bca7d30fdc662df0046c05ca739c0503" => :el_capitan
sha256 "35da1bacbc373d4430dccf0cba27cc84eebc69b6710b36efc63f236c61e09481" => :yosemite
sha256 "ab88b21eb30c66be5ba5c7ae77e991849e5370e395f85d2bd0824e78704efede" => :mavericks
end
depends_on "pkg-config" => :build
depends_on "intltool" => :build
depends_on "gettext"
depends_on "glib"
depends_on "gnutls"
depends_on "gsettings-desktop-schemas"
link_overwrite "lib/gio/modules"
def install
# Install files to `lib` instead of `HOMEBREW_PREFIX/lib`.
inreplace "configure", "$($PKG_CONFIG --variable giomoduledir gio-2.0)", lib/"gio/modules"
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-ca-certificates=#{etc}/openssl/cert.pem",
# Remove when p11-kit >= 0.20.7 builds on OSX
# see https://github.com/Homebrew/homebrew/issues/36323
# and https://bugs.freedesktop.org/show_bug.cgi?id=91602
"--without-pkcs11"
system "make", "install"
# Delete the cache, will regenerate it in post_install
rm lib/"gio/modules/giomodule.cache"
end
def post_install
system Formula["glib"].opt_bin/"gio-querymodules", HOMEBREW_PREFIX/"lib/gio/modules"
end
test do
(testpath/"gtls-test.c").write <<-EOS.undent
#include <gio/gio.h>
int main (int argc, char *argv[])
{
if (g_tls_backend_supports_tls (g_tls_backend_get_default()))
return 0;
else
return 1;
}
EOS
# From `pkg-config --cflags --libs gio-2.0`
flags = [
"-D_REENTRANT",
"-I#{HOMEBREW_PREFIX}/include/glib-2.0",
"-I#{HOMEBREW_PREFIX}/lib/glib-2.0/include",
"-I#{HOMEBREW_PREFIX}/opt/gettext/include",
"-L#{HOMEBREW_PREFIX}/lib",
"-L#{HOMEBREW_PREFIX}/opt/gettext/lib",
"-lgio-2.0", "-lgobject-2.0", "-lglib-2.0", "-lintl",
]
system ENV.cc, "gtls-test.c", "-o", "gtls-test", *flags
system "./gtls-test"
end
end
|
require 'formula'
# This formula installs files directly into the top-level gio modules
# directory, so it can't be bottled.
class GlibNetworking < Formula
homepage 'https://launchpad.net/glib-networking'
url 'http://ftp.gnome.org/pub/GNOME/sources/glib-networking/2.40/glib-networking-2.40.1.tar.xz'
sha256 '9fb3e54d049a480afdb814ff7452e7ab67e5d5f607ade230d7713f19922b5a28'
depends_on 'pkg-config' => :build
depends_on 'intltool' => :build
depends_on 'gettext'
depends_on 'glib'
depends_on 'gnutls'
depends_on 'gsettings-desktop-schemas'
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-ca-certificates=#{etc}/openssl/cert.pem"
system "make install"
end
end
glib-networking: add test
Closes #30581.
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
require 'formula'
# This formula installs files directly into the top-level gio modules
# directory, so it can't be bottled.
class GlibNetworking < Formula
homepage 'https://launchpad.net/glib-networking'
url 'http://ftp.gnome.org/pub/GNOME/sources/glib-networking/2.40/glib-networking-2.40.1.tar.xz'
sha256 '9fb3e54d049a480afdb814ff7452e7ab67e5d5f607ade230d7713f19922b5a28'
depends_on 'pkg-config' => :build
depends_on 'intltool' => :build
depends_on 'gettext'
depends_on 'glib'
depends_on 'gnutls'
depends_on 'gsettings-desktop-schemas'
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}",
"--with-ca-certificates=#{etc}/openssl/cert.pem"
system "make install"
end
test do
(testpath/"gtls-test.c").write <<-EOS.undent
#include <gio/gio.h>
int main (int argc, char *argv[])
{
if (g_tls_backend_supports_tls (g_tls_backend_get_default()))
return 0;
else
return 1;
}
EOS
# From `pkg-config --cflags --libs gio-2.0`
flags = [
"-D_REENTRANT",
"-I#{HOMEBREW_PREFIX}/include/glib-2.0",
"-I#{HOMEBREW_PREFIX}/lib/glib-2.0/include",
"-I#{HOMEBREW_PREFIX}/opt/gettext/include",
"-L#{HOMEBREW_PREFIX}/lib",
"-L#{HOMEBREW_PREFIX}/opt/gettext/lib",
"-lgio-2.0", "-lgobject-2.0", "-lglib-2.0", "-lintl"
]
system ENV.cc, "gtls-test.c", "-o", "gtls-test", *flags
system "./gtls-test"
end
end
|
# typed: false
# frozen_string_literal: true
require "delegate"
require "cask/cask_loader"
require "cli/args"
require "formulary"
require "missing_formula"
module Homebrew
module CLI
# Helper class for loading formulae/casks from named arguments.
#
# @api private
class NamedArgs < Array
def initialize(*args, parent: Args.new, override_spec: nil, force_bottle: false, flags: [])
@args = args
@override_spec = override_spec
@force_bottle = force_bottle
@flags = flags
@parent = parent
super(@args)
end
def to_casks
@to_casks ||= to_formulae_and_casks(only: :cask).freeze
end
def to_formulae
@to_formulae ||= to_formulae_and_casks(only: :formula).freeze
end
def to_formulae_and_casks(only: nil, method: nil)
@to_formulae_and_casks ||= {}
@to_formulae_and_casks[only] ||= begin
to_objects(only: only, method: method).reject { |o| o.is_a?(Tap) }.freeze
end
end
def to_formulae_to_casks(method: nil, only: nil)
@to_formulae_to_casks ||= {}
@to_formulae_to_casks[[method, only]] = to_formulae_and_casks(method: method, only: only)
.partition { |o| o.is_a?(Formula) }
.map(&:freeze).freeze
end
def to_formulae_and_casks_and_unavailable(method: nil)
@to_formulae_casks_unknowns ||= {}
@to_formulae_casks_unknowns[method] = downcased_unique_named.map do |name|
load_formula_or_cask(name, method: method)
rescue FormulaOrCaskUnavailableError => e
e
end.uniq.freeze
end
def load_formula_or_cask(name, only: nil, method: nil)
if only != :cask
begin
formula = case method
when nil, :factory
Formulary.factory(name, *spec, force_bottle: @force_bottle, flags: @flags)
when :resolve
Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags)
else
raise
end
warn_if_cask_conflicts(name, "formula") unless only == :formula
return formula
rescue FormulaUnavailableError => e
raise e if only == :formula
end
end
if only != :formula
begin
return Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent))
rescue Cask::CaskUnavailableError => e
raise e if only == :cask
end
end
raise FormulaOrCaskUnavailableError, name
end
private :load_formula_or_cask
def resolve_formula(name)
Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags)
end
private :resolve_formula
def to_resolved_formulae
@to_resolved_formulae ||= to_formulae_and_casks(only: :formula, method: :resolve)
.freeze
end
def to_resolved_formulae_to_casks(only: nil)
to_formulae_to_casks(method: :resolve, only: only)
end
# Convert named arguments to {Tap}, {Formula} or {Cask} objects.
# If both a formula and cask exist with the same name, returns the
# formula and prints a warning unless `only` is specified.
def to_objects(only: nil, method: nil)
@to_objects ||= {}
@to_objects[only] ||= downcased_unique_named.flat_map do |name|
next Tap.fetch(name) if only == :tap || (only.nil? && name.count("/") == 1 && !name.start_with?("./", "/"))
load_formula_or_cask(name, only: only, method: method)
end.uniq.freeze
end
private :to_objects
def to_formulae_paths
to_paths(only: :formulae)
end
# Keep existing paths and try to convert others to tap, formula or cask paths.
# If a cask and formula with the same name exist, includes both their paths
# unless `only` is specified.
def to_paths(only: nil)
@to_paths ||= {}
@to_paths[only] ||= downcased_unique_named.flat_map do |name|
if File.exist?(name)
Pathname(name)
elsif name.count("/") == 1
Tap.fetch(name).path
else
next Formulary.path(name) if only == :formulae
next Cask::CaskLoader.path(name) if only == :casks
formula_path = Formulary.path(name)
cask_path = Cask::CaskLoader.path(name)
paths = []
paths << formula_path if formula_path.exist?
paths << cask_path if cask_path.exist?
paths.empty? ? name : paths
end
end.uniq.freeze
end
def to_kegs
@to_kegs ||= downcased_unique_named.map do |name|
resolve_keg name
rescue NoSuchKegError => e
if (reason = Homebrew::MissingFormula.suggest_command(name, "uninstall"))
$stderr.puts reason
end
raise e
end.freeze
end
def to_kegs_to_casks
@to_kegs_to_casks ||= begin
kegs = []
casks = []
downcased_unique_named.each do |name|
kegs << resolve_keg(name)
warn_if_cask_conflicts(name, "keg")
rescue NoSuchKegError, FormulaUnavailableError
begin
casks << Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent))
rescue Cask::CaskUnavailableError
raise "No installed keg or cask with the name \"#{name}\""
end
end
[kegs.freeze, casks.freeze].freeze
end
end
def homebrew_tap_cask_names
downcased_unique_named.grep(HOMEBREW_CASK_TAP_CASK_REGEX)
end
private
def downcased_unique_named
# Only lowercase names, not paths, bottle filenames or URLs
map do |arg|
if arg.include?("/") || arg.end_with?(".tar.gz") || File.exist?(arg)
arg
else
arg.downcase
end
end.uniq
end
def spec
@override_spec
end
private :spec
def resolve_keg(name)
raise UsageError if name.blank?
require "keg"
rack = Formulary.to_rack(name.downcase)
dirs = rack.directory? ? rack.subdirs : []
raise NoSuchKegError, rack.basename if dirs.empty?
linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename
opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}"
begin
if opt_prefix.symlink? && opt_prefix.directory?
Keg.new(opt_prefix.resolved_path)
elsif linked_keg_ref.symlink? && linked_keg_ref.directory?
Keg.new(linked_keg_ref.resolved_path)
elsif dirs.length == 1
Keg.new(dirs.first)
else
f = if name.include?("/") || File.exist?(name)
Formulary.factory(name)
else
Formulary.from_rack(rack)
end
unless (prefix = f.latest_installed_prefix).directory?
raise MultipleVersionsInstalledError, <<~EOS
#{rack.basename} has multiple installed versions
Run `brew uninstall --force #{rack.basename}` to remove all versions.
EOS
end
Keg.new(prefix)
end
rescue FormulaUnavailableError
raise MultipleVersionsInstalledError, <<~EOS
Multiple kegs installed to #{rack}
However we don't know which one you refer to.
Please delete (with rm -rf!) all but one and then try again.
EOS
end
end
def warn_if_cask_conflicts(ref, loaded_type)
cask = Cask::CaskLoader.load ref
message = "Treating #{ref} as a #{loaded_type}."
message += " For the cask, use #{cask.tap.name}/#{cask.token}" if cask.tap.present?
opoo message.freeze
rescue Cask::CaskUnavailableError
# No ref conflict with a cask, do nothing
end
end
end
end
cli/named_args: don't convert to taps.
Fixes https://github.com/Homebrew/brew/issues/8966
# typed: false
# frozen_string_literal: true
require "delegate"
require "cask/cask_loader"
require "cli/args"
require "formulary"
require "missing_formula"
module Homebrew
module CLI
# Helper class for loading formulae/casks from named arguments.
#
# @api private
class NamedArgs < Array
def initialize(*args, parent: Args.new, override_spec: nil, force_bottle: false, flags: [])
@args = args
@override_spec = override_spec
@force_bottle = force_bottle
@flags = flags
@parent = parent
super(@args)
end
def to_casks
@to_casks ||= to_formulae_and_casks(only: :cask).freeze
end
def to_formulae
@to_formulae ||= to_formulae_and_casks(only: :formula).freeze
end
def to_formulae_and_casks(only: nil, method: nil)
@to_formulae_and_casks ||= {}
@to_formulae_and_casks[only] ||= begin
to_objects(only: only, method: method).reject { |o| o.is_a?(Tap) }.freeze
end
end
def to_formulae_to_casks(method: nil, only: nil)
@to_formulae_to_casks ||= {}
@to_formulae_to_casks[[method, only]] = to_formulae_and_casks(method: method, only: only)
.partition { |o| o.is_a?(Formula) }
.map(&:freeze).freeze
end
def to_formulae_and_casks_and_unavailable(method: nil)
@to_formulae_casks_unknowns ||= {}
@to_formulae_casks_unknowns[method] = downcased_unique_named.map do |name|
load_formula_or_cask(name, method: method)
rescue FormulaOrCaskUnavailableError => e
e
end.uniq.freeze
end
def load_formula_or_cask(name, only: nil, method: nil)
if only != :cask
begin
formula = case method
when nil, :factory
Formulary.factory(name, *spec, force_bottle: @force_bottle, flags: @flags)
when :resolve
Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags)
else
raise
end
warn_if_cask_conflicts(name, "formula") unless only == :formula
return formula
rescue FormulaUnavailableError => e
raise e if only == :formula
end
end
if only != :formula
begin
return Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent))
rescue Cask::CaskUnavailableError => e
raise e if only == :cask
end
end
raise FormulaOrCaskUnavailableError, name
end
private :load_formula_or_cask
def resolve_formula(name)
Formulary.resolve(name, spec: spec, force_bottle: @force_bottle, flags: @flags)
end
private :resolve_formula
def to_resolved_formulae
@to_resolved_formulae ||= to_formulae_and_casks(only: :formula, method: :resolve)
.freeze
end
def to_resolved_formulae_to_casks(only: nil)
to_formulae_to_casks(method: :resolve, only: only)
end
# Convert named arguments to {Formula} or {Cask} objects.
# If both a formula and cask exist with the same name, returns the
# formula and prints a warning unless `only` is specified.
def to_objects(only: nil, method: nil)
@to_objects ||= {}
@to_objects[only] ||= downcased_unique_named.flat_map do |name|
load_formula_or_cask(name, only: only, method: method)
end.uniq.freeze
end
private :to_objects
def to_formulae_paths
to_paths(only: :formulae)
end
# Keep existing paths and try to convert others to tap, formula or cask paths.
# If a cask and formula with the same name exist, includes both their paths
# unless `only` is specified.
def to_paths(only: nil)
@to_paths ||= {}
@to_paths[only] ||= downcased_unique_named.flat_map do |name|
if File.exist?(name)
Pathname(name)
elsif name.count("/") == 1
Tap.fetch(name).path
else
next Formulary.path(name) if only == :formulae
next Cask::CaskLoader.path(name) if only == :casks
formula_path = Formulary.path(name)
cask_path = Cask::CaskLoader.path(name)
paths = []
paths << formula_path if formula_path.exist?
paths << cask_path if cask_path.exist?
paths.empty? ? name : paths
end
end.uniq.freeze
end
def to_kegs
@to_kegs ||= downcased_unique_named.map do |name|
resolve_keg name
rescue NoSuchKegError => e
if (reason = Homebrew::MissingFormula.suggest_command(name, "uninstall"))
$stderr.puts reason
end
raise e
end.freeze
end
def to_kegs_to_casks
@to_kegs_to_casks ||= begin
kegs = []
casks = []
downcased_unique_named.each do |name|
kegs << resolve_keg(name)
warn_if_cask_conflicts(name, "keg")
rescue NoSuchKegError, FormulaUnavailableError
begin
casks << Cask::CaskLoader.load(name, config: Cask::Config.from_args(@parent))
rescue Cask::CaskUnavailableError
raise "No installed keg or cask with the name \"#{name}\""
end
end
[kegs.freeze, casks.freeze].freeze
end
end
def homebrew_tap_cask_names
downcased_unique_named.grep(HOMEBREW_CASK_TAP_CASK_REGEX)
end
private
def downcased_unique_named
# Only lowercase names, not paths, bottle filenames or URLs
map do |arg|
if arg.include?("/") || arg.end_with?(".tar.gz") || File.exist?(arg)
arg
else
arg.downcase
end
end.uniq
end
def spec
@override_spec
end
private :spec
def resolve_keg(name)
raise UsageError if name.blank?
require "keg"
rack = Formulary.to_rack(name.downcase)
dirs = rack.directory? ? rack.subdirs : []
raise NoSuchKegError, rack.basename if dirs.empty?
linked_keg_ref = HOMEBREW_LINKED_KEGS/rack.basename
opt_prefix = HOMEBREW_PREFIX/"opt/#{rack.basename}"
begin
if opt_prefix.symlink? && opt_prefix.directory?
Keg.new(opt_prefix.resolved_path)
elsif linked_keg_ref.symlink? && linked_keg_ref.directory?
Keg.new(linked_keg_ref.resolved_path)
elsif dirs.length == 1
Keg.new(dirs.first)
else
f = if name.include?("/") || File.exist?(name)
Formulary.factory(name)
else
Formulary.from_rack(rack)
end
unless (prefix = f.latest_installed_prefix).directory?
raise MultipleVersionsInstalledError, <<~EOS
#{rack.basename} has multiple installed versions
Run `brew uninstall --force #{rack.basename}` to remove all versions.
EOS
end
Keg.new(prefix)
end
rescue FormulaUnavailableError
raise MultipleVersionsInstalledError, <<~EOS
Multiple kegs installed to #{rack}
However we don't know which one you refer to.
Please delete (with rm -rf!) all but one and then try again.
EOS
end
end
def warn_if_cask_conflicts(ref, loaded_type)
cask = Cask::CaskLoader.load ref
message = "Treating #{ref} as a #{loaded_type}."
message += " For the cask, use #{cask.tap.name}/#{cask.token}" if cask.tap.present?
opoo message.freeze
rescue Cask::CaskUnavailableError
# No ref conflict with a cask, do nothing
end
end
end
end
|
#: * `bottle` [`--verbose`] [`--no-rebuild`|`--keep-old`] [`--skip-relocation`] [`--or-later`] [`--root-url=`<URL>] [`--force-core-tap`] <formulae>:
#: Generate a bottle (binary package) from a formula installed with
#: `--build-bottle`.
#:
#: If the formula specifies a rebuild version, it will be incremented in the
#: generated DSL. Passing `--keep-old` will attempt to keep it at its
#: original value, while `--no-rebuild` will remove it.
#:
#: If `--verbose` (or `-v`) is passed, print the bottling commands and any warnings
#: encountered.
#:
#: If `--skip-relocation` is passed, do not check if the bottle can be marked
#: as relocatable.
#:
#: If `--root-url` is passed, use the specified <URL> as the root of the
#: bottle's URL instead of Homebrew's default.
#:
#: If `--or-later` is passed, append _or_later to the bottle tag.
#:
#: If `--force-core-tap` is passed, build a bottle even if <formula> is not
#: in homebrew/core or any installed taps.
#:
#: * `bottle` `--merge` [`--keep-old`] [`--write` [`--no-commit`]] <formulae>:
#: Generate a bottle from a formula and print the new DSL merged into the
#: existing formula.
#:
#: If `--write` is passed, write the changes to the formula file. A new
#: commit will then be generated unless `--no-commit` is passed.
# Undocumented options:
# `--json` writes bottle information to a JSON file, which can be used as
# the argument for `--merge`.
require "formula"
require "utils/bottles"
require "tab"
require "keg"
require "formula_versions"
require "cli_parser"
require "utils/inreplace"
require "erb"
BOTTLE_ERB = <<-EOS.freeze
bottle do
<% if !root_url.start_with?(BottleSpecification::DEFAULT_DOMAIN) %>
root_url "<%= root_url %>"
<% end %>
<% if prefix != BottleSpecification::DEFAULT_PREFIX %>
prefix "<%= prefix %>"
<% end %>
<% if cellar.is_a? Symbol %>
cellar :<%= cellar %>
<% elsif cellar != BottleSpecification::DEFAULT_CELLAR %>
cellar "<%= cellar %>"
<% end %>
<% if rebuild.positive? %>
rebuild <%= rebuild %>
<% end %>
<% checksums.each do |checksum_type, checksum_values| %>
<% checksum_values.each do |checksum_value| %>
<% checksum, macos = checksum_value.shift %>
<%= checksum_type %> "<%= checksum %>" => :<%= macos %><%= "_or_later" if Homebrew.args.or_later? %>
<% end %>
<% end %>
end
EOS
MAXIMUM_STRING_MATCHES = 100
module Homebrew
module_function
def bottle
@args = Homebrew::CLI::Parser.parse do
switch "--merge"
switch "--skip-relocation"
switch "--force-core-tap"
switch "--no-rebuild"
switch "--keep-old"
switch "--write"
switch "--no-commit"
switch "--json"
switch "--or-later"
switch :verbose
switch :debug
flag "--root-url"
end
return merge if @args.merge?
ARGV.resolved_formulae.each do |f|
bottle_formula f
end
end
def keg_contain?(string, keg, ignores)
@put_string_exists_header, @put_filenames = nil
print_filename = lambda do |str, filename|
unless @put_string_exists_header
opoo "String '#{str}' still exists in these files:"
@put_string_exists_header = true
end
@put_filenames ||= []
return if @put_filenames.include?(filename)
puts Formatter.error(filename.to_s)
@put_filenames << filename
end
result = false
keg.each_unique_file_matching(string) do |file|
next if Metafiles::EXTENSIONS.include?(file.extname) # Skip document files.
linked_libraries = Keg.file_linked_libraries(file, string)
result ||= !linked_libraries.empty?
if Homebrew.args.verbose?
print_filename.call(string, file) unless linked_libraries.empty?
linked_libraries.each do |lib|
puts " #{Tty.bold}-->#{Tty.reset} links to #{lib}"
end
end
text_matches = []
# Use strings to search through the file for each string
Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io|
until io.eof?
str = io.readline.chomp
next if ignores.any? { |i| i =~ str }
next unless str.include? string
offset, match = str.split(" ", 2)
next if linked_libraries.include? match # Don't bother reporting a string if it was found by otool
result = true
text_matches << [match, offset]
end
end
next unless Homebrew.args.verbose? && !text_matches.empty?
print_filename.call(string, file)
text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset|
puts " #{Tty.bold}-->#{Tty.reset} match '#{match}' at offset #{Tty.bold}0x#{offset}#{Tty.reset}"
end
if text_matches.size > MAXIMUM_STRING_MATCHES
puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output"
end
end
keg_contain_absolute_symlink_starting_with?(string, keg) || result
end
def keg_contain_absolute_symlink_starting_with?(string, keg)
absolute_symlinks_start_with_string = []
keg.find do |pn|
next unless pn.symlink? && (link = pn.readlink).absolute?
absolute_symlinks_start_with_string << pn if link.to_s.start_with?(string)
end
if Homebrew.args.verbose?
unless absolute_symlinks_start_with_string.empty?
opoo "Absolute symlink starting with #{string}:"
absolute_symlinks_start_with_string.each do |pn|
puts " #{pn} -> #{pn.resolved_path}"
end
end
end
!absolute_symlinks_start_with_string.empty?
end
def bottle_output(bottle)
erb = ERB.new BOTTLE_ERB
erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, "")
end
def bottle_formula(f)
unless f.installed?
return ofail "Formula not installed or up-to-date: #{f.full_name}"
end
unless tap = f.tap
unless @args.force_core_tap?
return ofail "Formula not from core or any taps: #{f.full_name}"
end
tap = CoreTap.instance
end
if f.bottle_disabled?
ofail "Formula has disabled bottle: #{f.full_name}"
puts f.bottle_disable_reason
return
end
unless Utils::Bottles.built_as? f
return ofail "Formula not installed with '--build-bottle': #{f.full_name}"
end
return ofail "Formula has no stable version: #{f.full_name}" unless f.stable
if @args.no_rebuild? || !f.tap
rebuild = 0
elsif @args.keep_old?
rebuild = f.bottle_specification.rebuild
else
ohai "Determining #{f.full_name} bottle rebuild..."
versions = FormulaVersions.new(f)
rebuilds = versions.bottle_version_map("origin/master")[f.pkg_version]
rebuilds.pop if rebuilds.last.to_i.positive?
rebuild = rebuilds.empty? ? 0 : rebuilds.max.to_i + 1
end
filename = Bottle::Filename.create(f, Utils::Bottles.tag, rebuild)
bottle_path = Pathname.pwd/filename
tar_filename = filename.to_s.sub(/.gz$/, "")
tar_path = Pathname.pwd/tar_filename
prefix = HOMEBREW_PREFIX.to_s
repository = HOMEBREW_REPOSITORY.to_s
cellar = HOMEBREW_CELLAR.to_s
ohai "Bottling #{filename}..."
keg = Keg.new(f.prefix)
relocatable = false
skip_relocation = false
keg.lock do
original_tab = nil
changed_files = nil
begin
keg.delete_pyc_files!
unless @args.skip_relocation?
changed_files = keg.replace_locations_with_placeholders
end
Tab.clear_cache
tab = Tab.for_keg(keg)
original_tab = tab.dup
tab.poured_from_bottle = false
tab.HEAD = nil
tab.time = nil
tab.changed_files = changed_files
tab.write
keg.find do |file|
if file.symlink?
# Ruby does not support `File.lutime` yet.
# Shellout using `touch` to change modified time of symlink itself.
system "/usr/bin/touch", "-h",
"-t", tab.source_modified_time.strftime("%Y%m%d%H%M.%S"), file
else
file.utime(tab.source_modified_time, tab.source_modified_time)
end
end
cd cellar do
safe_system "tar", "cf", tar_path, "#{f.name}/#{f.pkg_version}"
tar_path.utime(tab.source_modified_time, tab.source_modified_time)
relocatable_tar_path = "#{f}-bottle.tar"
mv tar_path, relocatable_tar_path
# Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
# or an uncompressed tarball (and more bandwidth friendly).
safe_system "gzip", "-f", relocatable_tar_path
mv "#{relocatable_tar_path}.gz", bottle_path
end
if bottle_path.size > 1 * 1024 * 1024
ohai "Detecting if #{filename} is relocatable..."
end
if prefix == "/usr/local"
prefix_check = File.join(prefix, "opt")
else
prefix_check = prefix
end
ignores = []
if f.deps.any? { |dep| dep.name == "go" }
ignores << %r{#{Regexp.escape(HOMEBREW_CELLAR)}/go/[\d\.]+/libexec}
end
relocatable = true
if @args.skip_relocation?
skip_relocation = true
else
relocatable = false if keg_contain?(prefix_check, keg, ignores)
relocatable = false if keg_contain?(repository, keg, ignores)
relocatable = false if keg_contain?(cellar, keg, ignores)
if prefix != prefix_check
relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg)
relocatable = false if keg_contain?("#{prefix}/etc", keg, ignores)
relocatable = false if keg_contain?("#{prefix}/var", keg, ignores)
end
skip_relocation = relocatable && !keg.require_relocation?
end
puts if !relocatable && Homebrew.args.verbose?
rescue Interrupt
ignore_interrupts { bottle_path.unlink if bottle_path.exist? }
raise
ensure
ignore_interrupts do
original_tab&.write
unless @args.skip_relocation?
keg.replace_placeholders_with_locations changed_files
end
end
end
end
root_url = @args.root_url
bottle = BottleSpecification.new
bottle.tap = tap
bottle.root_url(root_url) if root_url
if relocatable
if skip_relocation
bottle.cellar :any_skip_relocation
else
bottle.cellar :any
end
else
bottle.cellar cellar
bottle.prefix prefix
end
bottle.rebuild rebuild
sha256 = bottle_path.sha256
bottle.sha256 sha256 => Utils::Bottles.tag
old_spec = f.bottle_specification
if @args.keep_old? && !old_spec.checksums.empty?
mismatches = [:root_url, :prefix, :cellar, :rebuild].reject do |key|
old_spec.send(key) == bottle.send(key)
end
mismatches.delete(:cellar) if old_spec.cellar == :any && bottle.cellar == :any_skip_relocation
unless mismatches.empty?
bottle_path.unlink if bottle_path.exist?
mismatches.map! do |key|
old_value = old_spec.send(key).inspect
value = bottle.send(key).inspect
"#{key}: old: #{old_value}, new: #{value}"
end
odie <<~EOS
--keep-old was passed but there are changes in:
#{mismatches.join("\n")}
EOS
end
end
output = bottle_output bottle
puts "./#{filename}"
puts output
return unless @args.json?
tag = Utils::Bottles.tag.to_s
tag += "_or_later" if args.or_later?
json = {
f.full_name => {
"formula" => {
"pkg_version" => f.pkg_version.to_s,
"path" => f.path.to_s.strip_prefix("#{HOMEBREW_REPOSITORY}/"),
},
"bottle" => {
"root_url" => bottle.root_url,
"prefix" => bottle.prefix,
"cellar" => bottle.cellar.to_s,
"rebuild" => bottle.rebuild,
"tags" => {
tag => {
"filename" => filename.to_s,
"sha256" => sha256,
},
},
},
"bintray" => {
"package" => Utils::Bottles::Bintray.package(f.name),
"repository" => Utils::Bottles::Bintray.repository(tap),
},
},
}
File.open("#{filename.prefix}.bottle.json", "w") do |file|
file.write JSON.generate json
end
end
def merge
write = @args.write?
bottles_hash = ARGV.named.reduce({}) do |hash, json_file|
deep_merge_hashes hash, JSON.parse(IO.read(json_file))
end
bottles_hash.each do |formula_name, bottle_hash|
ohai formula_name
bottle = BottleSpecification.new
bottle.root_url bottle_hash["bottle"]["root_url"]
cellar = bottle_hash["bottle"]["cellar"]
cellar = cellar.to_sym if ["any", "any_skip_relocation"].include?(cellar)
bottle.cellar cellar
bottle.prefix bottle_hash["bottle"]["prefix"]
bottle.rebuild bottle_hash["bottle"]["rebuild"]
bottle_hash["bottle"]["tags"].each do |tag, tag_hash|
bottle.sha256 tag_hash["sha256"] => tag.to_sym
end
output = bottle_output bottle
if write
path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s)
update_or_add = nil
Utils::Inreplace.inreplace(path) do |s|
if s.include? "bottle do"
update_or_add = "update"
if @args.keep_old?
mismatches = []
bottle_block_contents = s[/ bottle do(.+?)end\n/m, 1]
bottle_block_contents.lines.each do |line|
line = line.strip
next if line.empty?
key, old_value_original, _, tag = line.split " ", 4
valid_key = %w[root_url prefix cellar rebuild sha1 sha256].include? key
next unless valid_key
old_value = old_value_original.to_s.delete ":'\""
tag = tag.to_s.delete ":"
unless tag.empty?
if !bottle_hash["bottle"]["tags"][tag].to_s.empty?
mismatches << "#{key} => #{tag}"
else
bottle.send(key, old_value => tag.to_sym)
end
next
end
value_original = bottle_hash["bottle"][key]
value = value_original.to_s
next if key == "cellar" && old_value == "any" && value == "any_skip_relocation"
next unless old_value.empty? || value != old_value
old_value = old_value_original.inspect
value = value_original.inspect
mismatches << "#{key}: old: #{old_value}, new: #{value}"
end
unless mismatches.empty?
odie <<~EOS
--keep-old was passed but there are changes in:
#{mismatches.join("\n")}
EOS
end
output = bottle_output bottle
end
puts output
string = s.sub!(/ bottle do.+?end\n/m, output)
odie "Bottle block update failed!" unless string
else
if @args.keep_old?
odie "--keep-old was passed but there was no existing bottle block!"
end
puts output
update_or_add = "add"
if s.include? "stable do"
indent = s.slice(/^( +)stable do/, 1).length
string = s.sub!(/^ {#{indent}}stable do(.|\n)+?^ {#{indent}}end\n/m, '\0' + output + "\n")
else
string = s.sub!(
/(
(\ {2}\#[^\n]*\n)* # comments
\ {2}( # two spaces at the beginning
(url|head)\ ['"][\S\ ]+['"] # url or head with a string
(
,[\S\ ]*$ # url may have options
(\n^\ {3}[\S\ ]+$)* # options can be in multiple lines
)?|
(homepage|desc|sha1|sha256|version|mirror)\ ['"][\S\ ]+['"]| # specs with a string
revision\ \d+ # revision with a number
)\n+ # multiple empty lines
)+
/mx, '\0' + output + "\n"
)
end
odie "Bottle block addition failed!" unless string
end
end
unless @args.no_commit?
if ENV["HOMEBREW_GIT_NAME"]
ENV["GIT_AUTHOR_NAME"] =
ENV["GIT_COMMITTER_NAME"] =
ENV["HOMEBREW_GIT_NAME"]
end
if ENV["HOMEBREW_GIT_EMAIL"]
ENV["GIT_AUTHOR_EMAIL"] =
ENV["GIT_COMMITTER_EMAIL"] =
ENV["HOMEBREW_GIT_EMAIL"]
end
short_name = formula_name.split("/", -1).last
pkg_version = bottle_hash["formula"]["pkg_version"]
path.parent.cd do
safe_system "git", "commit", "--no-edit", "--verbose",
"--message=#{short_name}: #{update_or_add} #{pkg_version} bottle.",
"--", path
end
end
else
puts output
end
end
end
end
bottle: Use @args
#: * `bottle` [`--verbose`] [`--no-rebuild`|`--keep-old`] [`--skip-relocation`] [`--or-later`] [`--root-url=`<URL>] [`--force-core-tap`] <formulae>:
#: Generate a bottle (binary package) from a formula installed with
#: `--build-bottle`.
#:
#: If the formula specifies a rebuild version, it will be incremented in the
#: generated DSL. Passing `--keep-old` will attempt to keep it at its
#: original value, while `--no-rebuild` will remove it.
#:
#: If `--verbose` (or `-v`) is passed, print the bottling commands and any warnings
#: encountered.
#:
#: If `--skip-relocation` is passed, do not check if the bottle can be marked
#: as relocatable.
#:
#: If `--root-url` is passed, use the specified <URL> as the root of the
#: bottle's URL instead of Homebrew's default.
#:
#: If `--or-later` is passed, append _or_later to the bottle tag.
#:
#: If `--force-core-tap` is passed, build a bottle even if <formula> is not
#: in homebrew/core or any installed taps.
#:
#: * `bottle` `--merge` [`--keep-old`] [`--write` [`--no-commit`]] <formulae>:
#: Generate a bottle from a formula and print the new DSL merged into the
#: existing formula.
#:
#: If `--write` is passed, write the changes to the formula file. A new
#: commit will then be generated unless `--no-commit` is passed.
# Undocumented options:
# `--json` writes bottle information to a JSON file, which can be used as
# the argument for `--merge`.
require "formula"
require "utils/bottles"
require "tab"
require "keg"
require "formula_versions"
require "cli_parser"
require "utils/inreplace"
require "erb"
BOTTLE_ERB = <<-EOS.freeze
bottle do
<% if !root_url.start_with?(BottleSpecification::DEFAULT_DOMAIN) %>
root_url "<%= root_url %>"
<% end %>
<% if prefix != BottleSpecification::DEFAULT_PREFIX %>
prefix "<%= prefix %>"
<% end %>
<% if cellar.is_a? Symbol %>
cellar :<%= cellar %>
<% elsif cellar != BottleSpecification::DEFAULT_CELLAR %>
cellar "<%= cellar %>"
<% end %>
<% if rebuild.positive? %>
rebuild <%= rebuild %>
<% end %>
<% checksums.each do |checksum_type, checksum_values| %>
<% checksum_values.each do |checksum_value| %>
<% checksum, macos = checksum_value.shift %>
<%= checksum_type %> "<%= checksum %>" => :<%= macos %><%= "_or_later" if Homebrew.args.or_later? %>
<% end %>
<% end %>
end
EOS
MAXIMUM_STRING_MATCHES = 100
module Homebrew
module_function
def bottle
@args = Homebrew::CLI::Parser.parse do
switch "--merge"
switch "--skip-relocation"
switch "--force-core-tap"
switch "--no-rebuild"
switch "--keep-old"
switch "--write"
switch "--no-commit"
switch "--json"
switch "--or-later"
switch :verbose
switch :debug
flag "--root-url"
end
return merge if @args.merge?
ARGV.resolved_formulae.each do |f|
bottle_formula f
end
end
def keg_contain?(string, keg, ignores)
@put_string_exists_header, @put_filenames = nil
print_filename = lambda do |str, filename|
unless @put_string_exists_header
opoo "String '#{str}' still exists in these files:"
@put_string_exists_header = true
end
@put_filenames ||= []
return if @put_filenames.include?(filename)
puts Formatter.error(filename.to_s)
@put_filenames << filename
end
result = false
keg.each_unique_file_matching(string) do |file|
next if Metafiles::EXTENSIONS.include?(file.extname) # Skip document files.
linked_libraries = Keg.file_linked_libraries(file, string)
result ||= !linked_libraries.empty?
if Homebrew.args.verbose?
print_filename.call(string, file) unless linked_libraries.empty?
linked_libraries.each do |lib|
puts " #{Tty.bold}-->#{Tty.reset} links to #{lib}"
end
end
text_matches = []
# Use strings to search through the file for each string
Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io|
until io.eof?
str = io.readline.chomp
next if ignores.any? { |i| i =~ str }
next unless str.include? string
offset, match = str.split(" ", 2)
next if linked_libraries.include? match # Don't bother reporting a string if it was found by otool
result = true
text_matches << [match, offset]
end
end
next unless Homebrew.args.verbose? && !text_matches.empty?
print_filename.call(string, file)
text_matches.first(MAXIMUM_STRING_MATCHES).each do |match, offset|
puts " #{Tty.bold}-->#{Tty.reset} match '#{match}' at offset #{Tty.bold}0x#{offset}#{Tty.reset}"
end
if text_matches.size > MAXIMUM_STRING_MATCHES
puts "Only the first #{MAXIMUM_STRING_MATCHES} matches were output"
end
end
keg_contain_absolute_symlink_starting_with?(string, keg) || result
end
def keg_contain_absolute_symlink_starting_with?(string, keg)
absolute_symlinks_start_with_string = []
keg.find do |pn|
next unless pn.symlink? && (link = pn.readlink).absolute?
absolute_symlinks_start_with_string << pn if link.to_s.start_with?(string)
end
if Homebrew.args.verbose?
unless absolute_symlinks_start_with_string.empty?
opoo "Absolute symlink starting with #{string}:"
absolute_symlinks_start_with_string.each do |pn|
puts " #{pn} -> #{pn.resolved_path}"
end
end
end
!absolute_symlinks_start_with_string.empty?
end
def bottle_output(bottle)
erb = ERB.new BOTTLE_ERB
erb.result(bottle.instance_eval { binding }).gsub(/^\s*$\n/, "")
end
def bottle_formula(f)
unless f.installed?
return ofail "Formula not installed or up-to-date: #{f.full_name}"
end
unless tap = f.tap
unless @args.force_core_tap?
return ofail "Formula not from core or any taps: #{f.full_name}"
end
tap = CoreTap.instance
end
if f.bottle_disabled?
ofail "Formula has disabled bottle: #{f.full_name}"
puts f.bottle_disable_reason
return
end
unless Utils::Bottles.built_as? f
return ofail "Formula not installed with '--build-bottle': #{f.full_name}"
end
return ofail "Formula has no stable version: #{f.full_name}" unless f.stable
if @args.no_rebuild? || !f.tap
rebuild = 0
elsif @args.keep_old?
rebuild = f.bottle_specification.rebuild
else
ohai "Determining #{f.full_name} bottle rebuild..."
versions = FormulaVersions.new(f)
rebuilds = versions.bottle_version_map("origin/master")[f.pkg_version]
rebuilds.pop if rebuilds.last.to_i.positive?
rebuild = rebuilds.empty? ? 0 : rebuilds.max.to_i + 1
end
filename = Bottle::Filename.create(f, Utils::Bottles.tag, rebuild)
bottle_path = Pathname.pwd/filename
tar_filename = filename.to_s.sub(/.gz$/, "")
tar_path = Pathname.pwd/tar_filename
prefix = HOMEBREW_PREFIX.to_s
repository = HOMEBREW_REPOSITORY.to_s
cellar = HOMEBREW_CELLAR.to_s
ohai "Bottling #{filename}..."
keg = Keg.new(f.prefix)
relocatable = false
skip_relocation = false
keg.lock do
original_tab = nil
changed_files = nil
begin
keg.delete_pyc_files!
unless @args.skip_relocation?
changed_files = keg.replace_locations_with_placeholders
end
Tab.clear_cache
tab = Tab.for_keg(keg)
original_tab = tab.dup
tab.poured_from_bottle = false
tab.HEAD = nil
tab.time = nil
tab.changed_files = changed_files
tab.write
keg.find do |file|
if file.symlink?
# Ruby does not support `File.lutime` yet.
# Shellout using `touch` to change modified time of symlink itself.
system "/usr/bin/touch", "-h",
"-t", tab.source_modified_time.strftime("%Y%m%d%H%M.%S"), file
else
file.utime(tab.source_modified_time, tab.source_modified_time)
end
end
cd cellar do
safe_system "tar", "cf", tar_path, "#{f.name}/#{f.pkg_version}"
tar_path.utime(tab.source_modified_time, tab.source_modified_time)
relocatable_tar_path = "#{f}-bottle.tar"
mv tar_path, relocatable_tar_path
# Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
# or an uncompressed tarball (and more bandwidth friendly).
safe_system "gzip", "-f", relocatable_tar_path
mv "#{relocatable_tar_path}.gz", bottle_path
end
if bottle_path.size > 1 * 1024 * 1024
ohai "Detecting if #{filename} is relocatable..."
end
if prefix == "/usr/local"
prefix_check = File.join(prefix, "opt")
else
prefix_check = prefix
end
ignores = []
if f.deps.any? { |dep| dep.name == "go" }
ignores << %r{#{Regexp.escape(HOMEBREW_CELLAR)}/go/[\d\.]+/libexec}
end
relocatable = true
if @args.skip_relocation?
skip_relocation = true
else
relocatable = false if keg_contain?(prefix_check, keg, ignores)
relocatable = false if keg_contain?(repository, keg, ignores)
relocatable = false if keg_contain?(cellar, keg, ignores)
if prefix != prefix_check
relocatable = false if keg_contain_absolute_symlink_starting_with?(prefix, keg)
relocatable = false if keg_contain?("#{prefix}/etc", keg, ignores)
relocatable = false if keg_contain?("#{prefix}/var", keg, ignores)
end
skip_relocation = relocatable && !keg.require_relocation?
end
puts if !relocatable && Homebrew.args.verbose?
rescue Interrupt
ignore_interrupts { bottle_path.unlink if bottle_path.exist? }
raise
ensure
ignore_interrupts do
original_tab&.write
unless @args.skip_relocation?
keg.replace_placeholders_with_locations changed_files
end
end
end
end
root_url = @args.root_url
bottle = BottleSpecification.new
bottle.tap = tap
bottle.root_url(root_url) if root_url
if relocatable
if skip_relocation
bottle.cellar :any_skip_relocation
else
bottle.cellar :any
end
else
bottle.cellar cellar
bottle.prefix prefix
end
bottle.rebuild rebuild
sha256 = bottle_path.sha256
bottle.sha256 sha256 => Utils::Bottles.tag
old_spec = f.bottle_specification
if @args.keep_old? && !old_spec.checksums.empty?
mismatches = [:root_url, :prefix, :cellar, :rebuild].reject do |key|
old_spec.send(key) == bottle.send(key)
end
mismatches.delete(:cellar) if old_spec.cellar == :any && bottle.cellar == :any_skip_relocation
unless mismatches.empty?
bottle_path.unlink if bottle_path.exist?
mismatches.map! do |key|
old_value = old_spec.send(key).inspect
value = bottle.send(key).inspect
"#{key}: old: #{old_value}, new: #{value}"
end
odie <<~EOS
--keep-old was passed but there are changes in:
#{mismatches.join("\n")}
EOS
end
end
output = bottle_output bottle
puts "./#{filename}"
puts output
return unless @args.json?
tag = Utils::Bottles.tag.to_s
tag += "_or_later" if @args.or_later?
json = {
f.full_name => {
"formula" => {
"pkg_version" => f.pkg_version.to_s,
"path" => f.path.to_s.strip_prefix("#{HOMEBREW_REPOSITORY}/"),
},
"bottle" => {
"root_url" => bottle.root_url,
"prefix" => bottle.prefix,
"cellar" => bottle.cellar.to_s,
"rebuild" => bottle.rebuild,
"tags" => {
tag => {
"filename" => filename.to_s,
"sha256" => sha256,
},
},
},
"bintray" => {
"package" => Utils::Bottles::Bintray.package(f.name),
"repository" => Utils::Bottles::Bintray.repository(tap),
},
},
}
File.open("#{filename.prefix}.bottle.json", "w") do |file|
file.write JSON.generate json
end
end
def merge
write = @args.write?
bottles_hash = ARGV.named.reduce({}) do |hash, json_file|
deep_merge_hashes hash, JSON.parse(IO.read(json_file))
end
bottles_hash.each do |formula_name, bottle_hash|
ohai formula_name
bottle = BottleSpecification.new
bottle.root_url bottle_hash["bottle"]["root_url"]
cellar = bottle_hash["bottle"]["cellar"]
cellar = cellar.to_sym if ["any", "any_skip_relocation"].include?(cellar)
bottle.cellar cellar
bottle.prefix bottle_hash["bottle"]["prefix"]
bottle.rebuild bottle_hash["bottle"]["rebuild"]
bottle_hash["bottle"]["tags"].each do |tag, tag_hash|
bottle.sha256 tag_hash["sha256"] => tag.to_sym
end
output = bottle_output bottle
if write
path = Pathname.new((HOMEBREW_REPOSITORY/bottle_hash["formula"]["path"]).to_s)
update_or_add = nil
Utils::Inreplace.inreplace(path) do |s|
if s.include? "bottle do"
update_or_add = "update"
if @args.keep_old?
mismatches = []
bottle_block_contents = s[/ bottle do(.+?)end\n/m, 1]
bottle_block_contents.lines.each do |line|
line = line.strip
next if line.empty?
key, old_value_original, _, tag = line.split " ", 4
valid_key = %w[root_url prefix cellar rebuild sha1 sha256].include? key
next unless valid_key
old_value = old_value_original.to_s.delete ":'\""
tag = tag.to_s.delete ":"
unless tag.empty?
if !bottle_hash["bottle"]["tags"][tag].to_s.empty?
mismatches << "#{key} => #{tag}"
else
bottle.send(key, old_value => tag.to_sym)
end
next
end
value_original = bottle_hash["bottle"][key]
value = value_original.to_s
next if key == "cellar" && old_value == "any" && value == "any_skip_relocation"
next unless old_value.empty? || value != old_value
old_value = old_value_original.inspect
value = value_original.inspect
mismatches << "#{key}: old: #{old_value}, new: #{value}"
end
unless mismatches.empty?
odie <<~EOS
--keep-old was passed but there are changes in:
#{mismatches.join("\n")}
EOS
end
output = bottle_output bottle
end
puts output
string = s.sub!(/ bottle do.+?end\n/m, output)
odie "Bottle block update failed!" unless string
else
if @args.keep_old?
odie "--keep-old was passed but there was no existing bottle block!"
end
puts output
update_or_add = "add"
if s.include? "stable do"
indent = s.slice(/^( +)stable do/, 1).length
string = s.sub!(/^ {#{indent}}stable do(.|\n)+?^ {#{indent}}end\n/m, '\0' + output + "\n")
else
string = s.sub!(
/(
(\ {2}\#[^\n]*\n)* # comments
\ {2}( # two spaces at the beginning
(url|head)\ ['"][\S\ ]+['"] # url or head with a string
(
,[\S\ ]*$ # url may have options
(\n^\ {3}[\S\ ]+$)* # options can be in multiple lines
)?|
(homepage|desc|sha1|sha256|version|mirror)\ ['"][\S\ ]+['"]| # specs with a string
revision\ \d+ # revision with a number
)\n+ # multiple empty lines
)+
/mx, '\0' + output + "\n"
)
end
odie "Bottle block addition failed!" unless string
end
end
unless @args.no_commit?
if ENV["HOMEBREW_GIT_NAME"]
ENV["GIT_AUTHOR_NAME"] =
ENV["GIT_COMMITTER_NAME"] =
ENV["HOMEBREW_GIT_NAME"]
end
if ENV["HOMEBREW_GIT_EMAIL"]
ENV["GIT_AUTHOR_EMAIL"] =
ENV["GIT_COMMITTER_EMAIL"] =
ENV["HOMEBREW_GIT_EMAIL"]
end
short_name = formula_name.split("/", -1).last
pkg_version = bottle_hash["formula"]["pkg_version"]
path.parent.cd do
safe_system "git", "commit", "--no-edit", "--verbose",
"--message=#{short_name}: #{update_or_add} #{pkg_version} bottle.",
"--", path
end
end
else
puts output
end
end
end
end
|
task :typus do
system "rake -T typus --silent"
end
namespace :typus do
desc "Create Typus User `rake typus:seed email=foo@bar.com`"
task :seed => :environment do
include Authentication
##
# Create the new user with the params.
#
email = ENV['email']
password = ENV['password'] || generate_password
begin
typus_user = TypusUser.new(:email => email,
:password => password,
:password_confirmation => password,
:first_name => 'Typus',
:last_name => 'Admin',
:roles => 'admin',
:status => true)
if typus_user.save
puts "=> [Typus] Your new password is `#{password}`."
else
puts "=> [Typus] Please, provide a valid email. (rake typus:seed email=foo@bar.com)"
end
rescue
puts "=> [Typus] Run `script/generate typus_migration` to create required tables."
end
end
desc "Install plugin dependencies"
task :dependencies do
##
# Plugins
#
plugins = [ "git://github.com/thoughtbot/paperclip.git",
"git://github.com/rails/acts_as_list.git",
"git://github.com/rails/acts_as_tree.git" ]
plugins.each do |plugin_url|
puts "=> [Typus] Installing #{plugin_url}."
system "script/plugin install #{plugin_url}"
end
##
# Gems
#
gems = [ "paginator" ]
gems.each do |gem|
puts "=> [Typus] Installing #{gem}."
# If command fails, please, notify user!
if !(system "sudo gem install #{gem} --no-rdoc --no-ri")
puts "Installing gem #{gem} failed: Error code returned was #{$?}."
end
end
end
desc "Copy Typus images and stylesheets"
task :assets do
puts "=> [Typus] Copying images & stylesheets."
%w( images stylesheets ).each do |folder|
system "cp #{RAILS_ROOT}/vendor/plugins/typus/public/#{folder}/* #{RAILS_ROOT}/public/#{folder}/"
end
end
desc "Generates `config/typus_roles.yml`"
task :configure_roles do
begin
MODEL_DIR = File.join(RAILS_ROOT, "app/models")
Dir.chdir(MODEL_DIR)
models = Dir["*.rb"]
if !File.exists? ("#{RAILS_ROOT}/config/typus_roles.yml") or ENV['force']
require File.dirname(__FILE__) + '/../../../../config/environment'
typus = File.open("#{RAILS_ROOT}/config/typus_roles.yml", "w+")
typus.puts "admin:"
typus.puts " TypusUser: rw"
models.each do |model|
class_name = eval model.sub(/\.rb$/,'').camelize
if class_name.new.kind_of?(ActiveRecord::Base)
typus.puts " #{class_name}: rw"
end
end
typus.close
puts "=> [Typus] `config/typus_roles.yml` successfully created."
else
puts "=> [Typus] `config/typus_roles.yml` file already exists."
end
rescue Exception => e
puts "#{e.message}"
File.delete("#{RAILS_ROOT}/config/typus_roles.yml")
end
end
desc "Generates `config/typus.yml`"
task :configure do
begin
MODEL_DIR = File.join(RAILS_ROOT, "app/models")
Dir.chdir(MODEL_DIR)
models = Dir["*.rb"]
##
# If typus config file does not file exists or force param is not blank, configure
if !File.exists? ("#{RAILS_ROOT}/config/typus.yml") or ENV['force']
require File.dirname(__FILE__) + '/../../../../config/environment'
typus = File.open("#{RAILS_ROOT}/config/typus.yml", "w+")
typus.puts "# ------------------------------------------------"
typus.puts "# Typus Admin Configuration File"
typus.puts "# ------------------------------------------------"
typus.puts "#"
typus.puts "# Post:"
typus.puts "# fields:"
typus.puts "# list: title, category_id, created_at, status"
typus.puts "# form: title, body, status, created_at"
typus.puts "# relationship: title, status"
typus.puts "# actions:"
typus.puts "# list: cleanup"
typus.puts "# form: send_as_newsletter"
typus.puts "# order_by: created_at"
typus.puts "# relationships:"
typus.puts "# has_and_belongs_to_many: "
typus.puts "# has_many: "
typus.puts "# filters: status, created_at, category_id"
typus.puts "# search: title body"
typus.puts "# application: Content"
typus.puts "# description: Some text to describe the model"
typus.puts "#"
typus.puts "# ------------------------------------------------"
typus.puts ""
typus.close
models.each do |model|
class_name = eval model.sub(/\.rb$/,'').camelize
if class_name.new.kind_of?(ActiveRecord::Base)
class_attributes = class_name.new.attributes.keys
typus = File.open("#{RAILS_ROOT}/config/typus.yml", "a+")
typus.puts ""
typus.puts "#{class_name}:"
list = class_attributes
list.delete("content")
list.delete("body")
typus.puts " fields:"
typus.puts " list: #{list.join(", ")}"
typus.puts " form: #{list.join(", ")}"
typus.puts " relationship: #{list.join(", ")}"
typus.puts " actions:"
typus.puts " list:"
typus.puts " form:"
typus.puts " order_by:"
typus.puts " relationships:"
typus.puts " has_and_belongs_to_many:"
typus.puts " has_many:"
typus.puts " filters:"
typus.puts " search:"
typus.puts " application: Untitled"
typus.puts " description:"
typus.close
puts "=> [Typus] #{class_name} added to `config/typus.yml`"
end
end
else
puts "=> [Typus] Configuration file already exists."
end
rescue Exception => e
puts "#{e.message}"
File.delete("#{RAILS_ROOT}/config/typus.yml")
end
end
end
rake typus:roles shows the current roles setup
task :typus do
system "rake -T typus --silent"
end
namespace :typus do
desc "Create Typus User `rake typus:seed email=foo@bar.com`"
task :seed => :environment do
include Authentication
##
# Create the new user with the params.
#
email = ENV['email']
password = ENV['password'] || generate_password
begin
typus_user = TypusUser.new(:email => email,
:password => password,
:password_confirmation => password,
:first_name => 'Typus',
:last_name => 'Admin',
:roles => 'admin',
:status => true)
if typus_user.save
puts "=> [Typus] Your new password is `#{password}`."
else
puts "=> [Typus] Please, provide a valid email. (rake typus:seed email=foo@bar.com)"
end
rescue
puts "=> [Typus] Run `script/generate typus_migration` to create required tables."
end
end
desc "Install plugin dependencies"
task :dependencies do
##
# Plugins
#
plugins = [ "git://github.com/thoughtbot/paperclip.git",
"git://github.com/rails/acts_as_list.git",
"git://github.com/rails/acts_as_tree.git" ]
plugins.each do |plugin_url|
puts "=> [Typus] Installing #{plugin_url}."
system "script/plugin install #{plugin_url}"
end
##
# Gems
#
gems = [ "paginator" ]
gems.each do |gem|
puts "=> [Typus] Installing #{gem}."
# If command fails, please, notify user!
if !(system "sudo gem install #{gem} --no-rdoc --no-ri")
puts "Installing gem #{gem} failed: Error code returned was #{$?}."
end
end
end
desc "Copy Typus images and stylesheets"
task :assets do
puts "=> [Typus] Copying images & stylesheets."
%w( images stylesheets ).each do |folder|
system "cp #{RAILS_ROOT}/vendor/plugins/typus/public/#{folder}/* #{RAILS_ROOT}/public/#{folder}/"
end
end
desc "Show current roles"
task :roles => :environment do
puts "[Typus Roles]"
Typus::Configuration.roles.each do |role|
puts "- #{role.first.capitalize} has access to #{role.last.keys.join(", ")}"
end
end
desc "Generates `config/typus_roles.yml`"
task :configure_roles do
begin
MODEL_DIR = File.join(RAILS_ROOT, "app/models")
Dir.chdir(MODEL_DIR)
models = Dir["*.rb"]
if !File.exists? ("#{RAILS_ROOT}/config/typus_roles.yml") or ENV['force']
require File.dirname(__FILE__) + '/../../../../config/environment'
typus = File.open("#{RAILS_ROOT}/config/typus_roles.yml", "w+")
typus.puts "admin:"
typus.puts " TypusUser: rw"
models.each do |model|
class_name = eval model.sub(/\.rb$/,'').camelize
if class_name.new.kind_of?(ActiveRecord::Base)
typus.puts " #{class_name}: rw"
end
end
typus.close
puts "=> [Typus] `config/typus_roles.yml` successfully created."
else
puts "=> [Typus] `config/typus_roles.yml` file already exists."
end
rescue Exception => e
puts "#{e.message}"
File.delete("#{RAILS_ROOT}/config/typus_roles.yml")
end
end
desc "Generates `config/typus.yml`"
task :configure do
begin
MODEL_DIR = File.join(RAILS_ROOT, "app/models")
Dir.chdir(MODEL_DIR)
models = Dir["*.rb"]
##
# If typus config file does not file exists or force param is not blank, configure
if !File.exists? ("#{RAILS_ROOT}/config/typus.yml") or ENV['force']
require File.dirname(__FILE__) + '/../../../../config/environment'
typus = File.open("#{RAILS_ROOT}/config/typus.yml", "w+")
typus.puts "# ------------------------------------------------"
typus.puts "# Typus Admin Configuration File"
typus.puts "# ------------------------------------------------"
typus.puts "#"
typus.puts "# Post:"
typus.puts "# fields:"
typus.puts "# list: title, category_id, created_at, status"
typus.puts "# form: title, body, status, created_at"
typus.puts "# relationship: title, status"
typus.puts "# actions:"
typus.puts "# list: cleanup"
typus.puts "# form: send_as_newsletter"
typus.puts "# order_by: created_at"
typus.puts "# relationships:"
typus.puts "# has_and_belongs_to_many: "
typus.puts "# has_many: "
typus.puts "# filters: status, created_at, category_id"
typus.puts "# search: title body"
typus.puts "# application: Content"
typus.puts "# description: Some text to describe the model"
typus.puts "#"
typus.puts "# ------------------------------------------------"
typus.puts ""
typus.close
models.each do |model|
class_name = eval model.sub(/\.rb$/,'').camelize
if class_name.new.kind_of?(ActiveRecord::Base)
class_attributes = class_name.new.attributes.keys
typus = File.open("#{RAILS_ROOT}/config/typus.yml", "a+")
typus.puts ""
typus.puts "#{class_name}:"
list = class_attributes
list.delete("content")
list.delete("body")
typus.puts " fields:"
typus.puts " list: #{list.join(", ")}"
typus.puts " form: #{list.join(", ")}"
typus.puts " relationship: #{list.join(", ")}"
typus.puts " actions:"
typus.puts " list:"
typus.puts " form:"
typus.puts " order_by:"
typus.puts " relationships:"
typus.puts " has_and_belongs_to_many:"
typus.puts " has_many:"
typus.puts " filters:"
typus.puts " search:"
typus.puts " application: Untitled"
typus.puts " description:"
typus.close
puts "=> [Typus] #{class_name} added to `config/typus.yml`"
end
end
else
puts "=> [Typus] Configuration file already exists."
end
rescue Exception => e
puts "#{e.message}"
File.delete("#{RAILS_ROOT}/config/typus.yml")
end
end
end
|
TAP_MIGRATIONS = {
"agedu" => "homebrew/head-only",
"aimage" => "homebrew/boneyard",
"aplus" => "homebrew/boneyard",
"apple-gcc42" => "homebrew/dupes",
"appledoc" => "homebrew/boneyard",
"appswitch" => "homebrew/binary",
"atari++" => "homebrew/x11",
"authexec" => "homebrew/boneyard",
"aws-iam-tools" => "homebrew/boneyard",
"blackbox" => "homebrew/boneyard",
"bochs" => "homebrew/x11",
"boost149" => "homebrew/versions",
"cantera" => "homebrew/science",
"cardpeek" => "homebrew/x11",
"catdoc" => "homebrew/boneyard",
"clam" => "homebrew/boneyard",
"cloudfoundry-cli" => "pivotal/tap",
"clusterit" => "homebrew/x11",
"cmucl" => "homebrew/binary",
"comparepdf" => "homebrew/boneyard",
"connect" => "homebrew/boneyard",
"curlftpfs" => "homebrew/x11",
"cwm" => "homebrew/x11",
"dart" => "dart-lang/dart",
"ddd" => "homebrew/x11",
"denyhosts" => "homebrew/boneyard",
"dmenu" => "homebrew/x11",
"dotwrp" => "homebrew/science",
"drizzle" => "homebrew/boneyard",
"drush" => "homebrew/php",
"dsniff" => "homebrew/boneyard",
"dwm" => "homebrew/x11",
"dzen2" => "homebrew/x11",
"easy-tag" => "homebrew/x11",
"electric-fence" => "homebrew/boneyard",
"fceux" => "homebrew/games",
"feh" => "homebrew/x11",
"fox" => "homebrew/x11",
"freeglut" => "homebrew/x11",
"freerdp" => "homebrew/x11",
"fsv" => "homebrew/x11",
"geany" => "homebrew/x11",
"geda-gaf" => "homebrew/x11",
"geeqie" => "homebrew/x11",
"geomview" => "homebrew/x11",
"gerbv" => "homebrew/x11",
"ggobi" => "homebrew/x11",
"giblib" => "homebrew/x11",
"gkrellm" => "homebrew/x11",
"glade" => "homebrew/x11",
"gle" => "homebrew/x11",
"gnumeric" => "homebrew/x11",
"gnunet" => "homebrew/boneyard",
"gobby" => "homebrew/x11",
"gpredict" => "homebrew/x11",
"grace" => "homebrew/x11",
"grads" => "homebrew/binary",
"gromacs" => "homebrew/science",
"gsmartcontrol" => "homebrew/x11",
"gtk-chtheme" => "homebrew/x11",
"gtksourceviewmm" => "homebrew/x11",
"gtksourceviewmm3" => "homebrew/x11",
"gtkwave" => "homebrew/x11",
"gupnp-tools" => "homebrew/x11",
"hatari" => "homebrew/x11",
"helios" => "spotify/public",
"hexchat" => "homebrew/x11",
"hllib" => "homebrew/boneyard",
"hugs98" => "homebrew/boneyard",
"hwloc" => "homebrew/science",
"imake" => "homebrew/x11",
"inkscape" => "homebrew/x11",
"ipopt" => "homebrew/science",
"iptux" => "homebrew/x11",
"itsol" => "homebrew/science",
"iulib" => "homebrew/boneyard",
"jscoverage" => "homebrew/boneyard",
"jsl" => "homebrew/binary",
"jstalk" => "homebrew/boneyard",
"justniffer" => "homebrew/boneyard",
"kerl" => "homebrew/head-only",
"kernagic" => "homebrew/x11",
"kismet" => "homebrew/boneyard",
"klavaro" => "homebrew/x11",
"libdlna" => "homebrew/boneyard",
"libgtextutils" => "homebrew/science",
"librets" => "homebrew/boneyard",
"libspotify" => "homebrew/binary",
"lmutil" => "homebrew/binary",
"meld" => "homebrew/x11",
"mesalib-glw" => "homebrew/x11",
"mess" => "homebrew/games",
"metalua" => "homebrew/boneyard",
"mit-scheme" => "homebrew/x11",
"mlkit" => "homebrew/boneyard",
"mlton" => "homebrew/boneyard",
"morse" => "homebrew/x11",
"mpio" => "homebrew/boneyard",
"mscgen" => "homebrew/x11",
"msgpack-rpc" => "homebrew/boneyard",
"mupdf" => "homebrew/x11",
"mydumper" => "homebrew/boneyard",
"nlopt" => "homebrew/science",
"octave" => "homebrew/science",
"opencv" => "homebrew/science",
"openfst" => "homebrew/science",
"opengrm-ngram" => "homebrew/science",
"pan" => "homebrew/boneyard",
"pari" => "homebrew/x11",
"pcb" => "homebrew/x11",
"pdf2image" => "homebrew/x11",
"pdf2svg" => "homebrew/x11",
"pgplot" => "homebrew/x11",
"pixie" => "homebrew/x11",
"pjsip" => "homebrew/boneyard",
"pocl" => "homebrew/science",
"prooftree" => "homebrew/x11",
"py3cairo" => "homebrew/x11",
"pyxplot" => "homebrew/x11",
"qfits" => "homebrew/boneyard",
"qrupdate" => "homebrew/science",
"rdesktop" => "homebrew/x11",
"rxvt-unicode" => "homebrew/x11",
"salt" => "homebrew/science",
"scantailor" => "homebrew/x11",
"shark" => "homebrew/boneyard",
"slicot" => "homebrew/science",
"smartsim" => "homebrew/x11",
"solfege" => "homebrew/boneyard",
"sptk" => "homebrew/x11",
"sundials" => "homebrew/science",
"swi-prolog" => "homebrew/x11",
"sxiv" => "homebrew/x11",
"sylpheed" => "homebrew/x11",
"syslog-ng" => "homebrew/boneyard",
"tabbed" => "homebrew/x11",
"terminator" => "homebrew/x11",
"tetgen" => "homebrew/science",
"texmacs" => "homebrew/boneyard",
"tiger-vnc" => "homebrew/x11",
"tmap" => "homebrew/boneyard",
"transmission-remote-gtk" => "homebrew/x11",
"ume" => "homebrew/games",
"upnp-router-control" => "homebrew/x11",
"urweb" => "homebrew/boneyard",
"ushare" => "homebrew/boneyard",
"viewglob" => "homebrew/x11",
"wkhtmltopdf" => "homebrew/boneyard",
"wmctrl" => "homebrew/x11",
"x3270" => "homebrew/x11",
"xchat" => "homebrew/x11",
"xclip" => "homebrew/x11",
"xdotool" => "homebrew/x11",
"xdu" => "homebrew/x11",
"xournal" => "homebrew/x11",
"xpa" => "homebrew/x11",
"xpdf" => "homebrew/x11",
"xplot" => "homebrew/x11",
"xspringies" => "homebrew/x11",
"yarp" => "homebrew/x11",
}
newick-utils 1.6: Move to Homebrew/science
Closes Homebrew/homebrew#35671.
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
TAP_MIGRATIONS = {
"agedu" => "homebrew/head-only",
"aimage" => "homebrew/boneyard",
"aplus" => "homebrew/boneyard",
"apple-gcc42" => "homebrew/dupes",
"appledoc" => "homebrew/boneyard",
"appswitch" => "homebrew/binary",
"atari++" => "homebrew/x11",
"authexec" => "homebrew/boneyard",
"aws-iam-tools" => "homebrew/boneyard",
"blackbox" => "homebrew/boneyard",
"bochs" => "homebrew/x11",
"boost149" => "homebrew/versions",
"cantera" => "homebrew/science",
"cardpeek" => "homebrew/x11",
"catdoc" => "homebrew/boneyard",
"clam" => "homebrew/boneyard",
"cloudfoundry-cli" => "pivotal/tap",
"clusterit" => "homebrew/x11",
"cmucl" => "homebrew/binary",
"comparepdf" => "homebrew/boneyard",
"connect" => "homebrew/boneyard",
"curlftpfs" => "homebrew/x11",
"cwm" => "homebrew/x11",
"dart" => "dart-lang/dart",
"ddd" => "homebrew/x11",
"denyhosts" => "homebrew/boneyard",
"dmenu" => "homebrew/x11",
"dotwrp" => "homebrew/science",
"drizzle" => "homebrew/boneyard",
"drush" => "homebrew/php",
"dsniff" => "homebrew/boneyard",
"dwm" => "homebrew/x11",
"dzen2" => "homebrew/x11",
"easy-tag" => "homebrew/x11",
"electric-fence" => "homebrew/boneyard",
"fceux" => "homebrew/games",
"feh" => "homebrew/x11",
"fox" => "homebrew/x11",
"freeglut" => "homebrew/x11",
"freerdp" => "homebrew/x11",
"fsv" => "homebrew/x11",
"geany" => "homebrew/x11",
"geda-gaf" => "homebrew/x11",
"geeqie" => "homebrew/x11",
"geomview" => "homebrew/x11",
"gerbv" => "homebrew/x11",
"ggobi" => "homebrew/x11",
"giblib" => "homebrew/x11",
"gkrellm" => "homebrew/x11",
"glade" => "homebrew/x11",
"gle" => "homebrew/x11",
"gnumeric" => "homebrew/x11",
"gnunet" => "homebrew/boneyard",
"gobby" => "homebrew/x11",
"gpredict" => "homebrew/x11",
"grace" => "homebrew/x11",
"grads" => "homebrew/binary",
"gromacs" => "homebrew/science",
"gsmartcontrol" => "homebrew/x11",
"gtk-chtheme" => "homebrew/x11",
"gtksourceviewmm" => "homebrew/x11",
"gtksourceviewmm3" => "homebrew/x11",
"gtkwave" => "homebrew/x11",
"gupnp-tools" => "homebrew/x11",
"hatari" => "homebrew/x11",
"helios" => "spotify/public",
"hexchat" => "homebrew/x11",
"hllib" => "homebrew/boneyard",
"hugs98" => "homebrew/boneyard",
"hwloc" => "homebrew/science",
"imake" => "homebrew/x11",
"inkscape" => "homebrew/x11",
"ipopt" => "homebrew/science",
"iptux" => "homebrew/x11",
"itsol" => "homebrew/science",
"iulib" => "homebrew/boneyard",
"jscoverage" => "homebrew/boneyard",
"jsl" => "homebrew/binary",
"jstalk" => "homebrew/boneyard",
"justniffer" => "homebrew/boneyard",
"kerl" => "homebrew/head-only",
"kernagic" => "homebrew/x11",
"kismet" => "homebrew/boneyard",
"klavaro" => "homebrew/x11",
"libdlna" => "homebrew/boneyard",
"libgtextutils" => "homebrew/science",
"librets" => "homebrew/boneyard",
"libspotify" => "homebrew/binary",
"lmutil" => "homebrew/binary",
"meld" => "homebrew/x11",
"mesalib-glw" => "homebrew/x11",
"mess" => "homebrew/games",
"metalua" => "homebrew/boneyard",
"mit-scheme" => "homebrew/x11",
"mlkit" => "homebrew/boneyard",
"mlton" => "homebrew/boneyard",
"morse" => "homebrew/x11",
"mpio" => "homebrew/boneyard",
"mscgen" => "homebrew/x11",
"msgpack-rpc" => "homebrew/boneyard",
"mupdf" => "homebrew/x11",
"mydumper" => "homebrew/boneyard",
"newick-utils" => "homebrew/science",
"nlopt" => "homebrew/science",
"octave" => "homebrew/science",
"opencv" => "homebrew/science",
"openfst" => "homebrew/science",
"opengrm-ngram" => "homebrew/science",
"pan" => "homebrew/boneyard",
"pari" => "homebrew/x11",
"pcb" => "homebrew/x11",
"pdf2image" => "homebrew/x11",
"pdf2svg" => "homebrew/x11",
"pgplot" => "homebrew/x11",
"pixie" => "homebrew/x11",
"pjsip" => "homebrew/boneyard",
"pocl" => "homebrew/science",
"prooftree" => "homebrew/x11",
"py3cairo" => "homebrew/x11",
"pyxplot" => "homebrew/x11",
"qfits" => "homebrew/boneyard",
"qrupdate" => "homebrew/science",
"rdesktop" => "homebrew/x11",
"rxvt-unicode" => "homebrew/x11",
"salt" => "homebrew/science",
"scantailor" => "homebrew/x11",
"shark" => "homebrew/boneyard",
"slicot" => "homebrew/science",
"smartsim" => "homebrew/x11",
"solfege" => "homebrew/boneyard",
"sptk" => "homebrew/x11",
"sundials" => "homebrew/science",
"swi-prolog" => "homebrew/x11",
"sxiv" => "homebrew/x11",
"sylpheed" => "homebrew/x11",
"syslog-ng" => "homebrew/boneyard",
"tabbed" => "homebrew/x11",
"terminator" => "homebrew/x11",
"tetgen" => "homebrew/science",
"texmacs" => "homebrew/boneyard",
"tiger-vnc" => "homebrew/x11",
"tmap" => "homebrew/boneyard",
"transmission-remote-gtk" => "homebrew/x11",
"ume" => "homebrew/games",
"upnp-router-control" => "homebrew/x11",
"urweb" => "homebrew/boneyard",
"ushare" => "homebrew/boneyard",
"viewglob" => "homebrew/x11",
"wkhtmltopdf" => "homebrew/boneyard",
"wmctrl" => "homebrew/x11",
"x3270" => "homebrew/x11",
"xchat" => "homebrew/x11",
"xclip" => "homebrew/x11",
"xdotool" => "homebrew/x11",
"xdu" => "homebrew/x11",
"xournal" => "homebrew/x11",
"xpa" => "homebrew/x11",
"xpdf" => "homebrew/x11",
"xplot" => "homebrew/x11",
"xspringies" => "homebrew/x11",
"yarp" => "homebrew/x11",
}
|
TAP_MIGRATIONS = {
"adobe-air-sdk" => "homebrew/binary",
"afuse" => "homebrew/fuse",
"aimage" => "homebrew/boneyard",
"aplus" => "homebrew/boneyard",
"apple-gcc42" => "homebrew/dupes",
"appswitch" => "homebrew/binary",
"archivemount" => "homebrew/fuse",
"atari++" => "homebrew/x11",
"auctex" => "homebrew/tex",
"authexec" => "homebrew/boneyard",
"avfs" => "homebrew/fuse",
"aws-iam-tools" => "homebrew/boneyard",
"awsenv" => "Luzifer/tools",
"bbcp" => "homebrew/head-only",
"bcwipe" => "homebrew/boneyard",
"bindfs" => "homebrew/fuse",
"blackbox" => "homebrew/boneyard",
"bochs" => "homebrew/x11",
"boost149" => "homebrew/versions",
"cantera" => "homebrew/science",
"cardpeek" => "homebrew/x11",
"catdoc" => "homebrew/boneyard",
"cdf" => "homebrew/boneyard",
"cdimgtools" => "homebrew/boneyard",
"celt" => "homebrew/boneyard",
"chktex" => "homebrew/tex",
"clam" => "homebrew/boneyard",
"clay" => "homebrew/boneyard",
"cloudfoundry-cli" => "pivotal/tap",
"clusterit" => "homebrew/x11",
"cmucl" => "homebrew/binary",
"comparepdf" => "homebrew/boneyard",
"connect" => "homebrew/boneyard",
"coremod" => "homebrew/boneyard",
"curlftpfs" => "homebrew/x11",
"cwm" => "homebrew/x11",
"dart" => "dart-lang/dart",
"datamash" => "homebrew/science",
"dbslayer" => "homebrew/boneyard",
"ddd" => "homebrew/x11",
"denyhosts" => "homebrew/boneyard",
"dgtal" => "homebrew/science",
"djmount" => "homebrew/fuse",
"dmenu" => "homebrew/x11",
"dotwrp" => "homebrew/science",
"drizzle" => "homebrew/boneyard",
"drush" => "homebrew/php",
"dsniff" => "homebrew/boneyard",
"dupx" => "homebrew/boneyard",
"dwm" => "homebrew/x11",
"dzen2" => "homebrew/x11",
"easy-tag" => "homebrew/x11",
"echoping" => "homebrew/boneyard",
"electric-fence" => "homebrew/boneyard",
"encfs" => "homebrew/fuse",
"ext2fuse" => "homebrew/fuse",
"ext4fuse" => "homebrew/fuse",
"fceux" => "homebrew/games",
"feh" => "homebrew/x11",
"ffts" => "homebrew/boneyard",
"figtoipe" => "homebrew/head-only",
"fox" => "homebrew/x11",
"freeglut" => "homebrew/x11",
"freerdp" => "homebrew/x11",
"fsv" => "homebrew/boneyard",
"fuse-zip" => "homebrew/fuse",
"fuse4x" => "homebrew/fuse",
"fuse4x-kext" => "homebrew/fuse",
"gant" => "homebrew/boneyard",
"gcsfuse" => "homebrew/fuse",
"gdrive" => "homebrew/boneyard",
"geany" => "homebrew/x11",
"geda-gaf" => "homebrew/x11",
"geeqie" => "homebrew/x11",
"geomview" => "homebrew/x11",
"gerbv" => "homebrew/x11",
"ggobi" => "homebrew/x11",
"giblib" => "homebrew/x11",
"git-encrypt" => "homebrew/boneyard",
"git-flow-clone" => "homebrew/boneyard",
"git-latexdiff" => "homebrew/tex",
"gitfs" => "homebrew/fuse",
"glade" => "homebrew/x11",
"gle" => "homebrew/x11",
"gnumeric" => "homebrew/x11",
"gnunet" => "homebrew/boneyard",
"gobby" => "homebrew/x11",
"googlecl" => "homebrew/boneyard",
"gpredict" => "homebrew/x11",
"gptfdisk" => "homebrew/boneyard",
"grace" => "homebrew/x11",
"grads" => "homebrew/binary",
"graylog2-server" => "homebrew/boneyard",
"gromacs" => "homebrew/science",
"gsmartcontrol" => "homebrew/x11",
"gtk-chtheme" => "homebrew/x11",
"gtkglarea" => "homebrew/boneyard",
"gtksourceviewmm" => "homebrew/x11",
"gtksourceviewmm3" => "homebrew/x11",
"gtkwave" => "homebrew/x11",
"guilt" => "homebrew/boneyard",
"gv" => "homebrew/x11",
"hatari" => "homebrew/x11",
"helios" => "spotify/public",
"hexchat" => "homebrew/x11",
"hllib" => "homebrew/boneyard",
"honeyd" => "homebrew/boneyard",
"hugs98" => "homebrew/boneyard",
"hwloc" => "homebrew/science",
"ifuse" => "homebrew/fuse",
"imake" => "homebrew/x11",
"inkscape" => "homebrew/x11",
"iojs" => "homebrew/versions",
"ipe" => "homebrew/boneyard",
"ipopt" => "homebrew/science",
"iptux" => "homebrew/x11",
"itsol" => "homebrew/science",
"iulib" => "homebrew/boneyard",
"jscoverage" => "homebrew/boneyard",
"jsl" => "homebrew/binary",
"jstalk" => "homebrew/boneyard",
"justniffer" => "homebrew/boneyard",
"kbtin" => "homebrew/boneyard",
"kerl" => "homebrew/head-only",
"kernagic" => "homebrew/x11",
"kismet" => "homebrew/boneyard",
"klavaro" => "homebrew/x11",
"kumofs" => "homebrew/boneyard",
"latex-mk" => "homebrew/tex",
"libdlna" => "homebrew/boneyard",
"libgtextutils" => "homebrew/science",
"libqxt" => "homebrew/boneyard",
"librets" => "homebrew/boneyard",
"libspotify" => "homebrew/binary",
"lilypond" => "homebrew/tex",
"lmutil" => "homebrew/binary",
"magit" => "homebrew/emacs",
"meld" => "homebrew/x11",
"mesalib-glw" => "homebrew/x11",
"mess" => "homebrew/games",
"metalua" => "homebrew/boneyard",
"mit-scheme" => "homebrew/x11",
"mlkit" => "homebrew/boneyard",
"mlton" => "homebrew/boneyard",
"morse" => "homebrew/x11",
"mp3fs" => "homebrew/fuse",
"mpio" => "homebrew/boneyard",
"mscgen" => "homebrew/x11",
"msgpack-rpc" => "homebrew/boneyard",
"mupdf" => "homebrew/x11",
"mysql-connector-odbc" => "homebrew/boneyard",
"mysql-proxy" => "homebrew/boneyard",
"mysqlreport" => "homebrew/boneyard",
"net6" => "homebrew/boneyard",
"newick-utils" => "homebrew/science",
"nlopt" => "homebrew/science",
"ntfs-3g" => "homebrew/fuse",
"octave" => "homebrew/science",
"opencv" => "homebrew/science",
"openfst" => "homebrew/science",
"opengrm-ngram" => "homebrew/science",
"ori" => "homebrew/fuse",
"p11-kit" => "homebrew/boneyard",
"pan" => "homebrew/boneyard",
"paq8px" => "homebrew/boneyard",
"par2tbb" => "homebrew/boneyard",
"pari" => "homebrew/x11",
"pathfinder" => "homebrew/boneyard",
"pcb" => "homebrew/x11",
"pdf-tools" => "homebrew/emacs",
"pdf2image" => "homebrew/x11",
"pdfjam" => "homebrew/tex",
"pdftoipe" => "homebrew/head-only",
"pebble-sdk" => "pebble/pebble-sdk",
"pgplot" => "homebrew/x11",
"pixie" => "homebrew/x11",
"pjsip" => "homebrew/boneyard",
"pocl" => "homebrew/science",
"pplatex" => "homebrew/tex",
"prooftree" => "homebrew/x11",
"pulse" => "homebrew/boneyard",
"pyenv-pip-rehash" => "homebrew/boneyard",
"pyxplot" => "homebrew/x11",
"qfits" => "homebrew/boneyard",
"qi" => "homebrew/boneyard",
"qiv" => "homebrew/boneyard",
"qrupdate" => "homebrew/science",
"rdesktop" => "homebrew/x11",
"rocket" => "homebrew/boneyard",
"rofs-filtered" => "homebrew/fuse",
"rxvt-unicode" => "homebrew/x11",
"s3-backer" => "homebrew/fuse",
"s3fs" => "homebrew/fuse",
"salt" => "homebrew/science",
"scantailor" => "homebrew/x11",
"sdelta3" => "homebrew/boneyard",
"sedna" => "homebrew/boneyard",
"shark" => "homebrew/science",
"shell.fm" => "homebrew/boneyard",
"simple-mtpfs" => "homebrew/fuse",
"sitecopy" => "homebrew/boneyard",
"slicot" => "homebrew/science",
"smartsim" => "homebrew/x11",
"solfege" => "homebrew/boneyard",
"sptk" => "homebrew/x11",
"sshfs" => "homebrew/fuse",
"stormfs" => "homebrew/fuse",
"sundials" => "homebrew/science",
"swi-prolog" => "homebrew/x11",
"sxiv" => "homebrew/x11",
"sylpheed" => "homebrew/x11",
"syslog-ng" => "homebrew/boneyard",
"tabbed" => "homebrew/x11",
"terminator" => "homebrew/x11",
"tetgen" => "homebrew/science",
"texmacs" => "homebrew/boneyard",
"texwrapper" => "homebrew/tex",
"ticcutils" => "homebrew/science",
"tiger-vnc" => "homebrew/x11",
"timbl" => "homebrew/science",
"tmap" => "homebrew/boneyard",
"transmission-remote-gtk" => "homebrew/x11",
"tup" => "homebrew/fuse",
"uim" => "homebrew/x11",
"ume" => "homebrew/games",
"upnp-router-control" => "homebrew/x11",
"urweb" => "homebrew/boneyard",
"ushare" => "homebrew/boneyard",
"viewglob" => "homebrew/boneyard",
"vobcopy" => "homebrew/boneyard",
"wdfs" => "homebrew/fuse",
"whereami" => "homebrew/boneyard",
"wkhtmltopdf" => "homebrew/boneyard",
"wmctrl" => "homebrew/x11",
"wopr" => "homebrew/science",
"wps2odt" => "homebrew/boneyard",
"x3270" => "homebrew/x11",
"xar" => "homebrew/dupes",
"xastir" => "homebrew/x11",
"xchat" => "homebrew/x11",
"xclip" => "homebrew/x11",
"xdotool" => "homebrew/x11",
"xdu" => "homebrew/x11",
"xmount" => "homebrew/fuse",
"xournal" => "homebrew/x11",
"xpa" => "homebrew/x11",
"xpdf" => "homebrew/x11",
"xplot" => "homebrew/x11",
"xspringies" => "homebrew/x11",
"yarp" => "homebrew/x11",
"ydict" => "homebrew/boneyard",
"zenity" => "homebrew/x11",
}
geany: migrate from x11
TAP_MIGRATIONS = {
"adobe-air-sdk" => "homebrew/binary",
"afuse" => "homebrew/fuse",
"aimage" => "homebrew/boneyard",
"aplus" => "homebrew/boneyard",
"apple-gcc42" => "homebrew/dupes",
"appswitch" => "homebrew/binary",
"archivemount" => "homebrew/fuse",
"atari++" => "homebrew/x11",
"auctex" => "homebrew/tex",
"authexec" => "homebrew/boneyard",
"avfs" => "homebrew/fuse",
"aws-iam-tools" => "homebrew/boneyard",
"awsenv" => "Luzifer/tools",
"bbcp" => "homebrew/head-only",
"bcwipe" => "homebrew/boneyard",
"bindfs" => "homebrew/fuse",
"blackbox" => "homebrew/boneyard",
"bochs" => "homebrew/x11",
"boost149" => "homebrew/versions",
"cantera" => "homebrew/science",
"cardpeek" => "homebrew/x11",
"catdoc" => "homebrew/boneyard",
"cdf" => "homebrew/boneyard",
"cdimgtools" => "homebrew/boneyard",
"celt" => "homebrew/boneyard",
"chktex" => "homebrew/tex",
"clam" => "homebrew/boneyard",
"clay" => "homebrew/boneyard",
"cloudfoundry-cli" => "pivotal/tap",
"clusterit" => "homebrew/x11",
"cmucl" => "homebrew/binary",
"comparepdf" => "homebrew/boneyard",
"connect" => "homebrew/boneyard",
"coremod" => "homebrew/boneyard",
"curlftpfs" => "homebrew/x11",
"cwm" => "homebrew/x11",
"dart" => "dart-lang/dart",
"datamash" => "homebrew/science",
"dbslayer" => "homebrew/boneyard",
"ddd" => "homebrew/x11",
"denyhosts" => "homebrew/boneyard",
"dgtal" => "homebrew/science",
"djmount" => "homebrew/fuse",
"dmenu" => "homebrew/x11",
"dotwrp" => "homebrew/science",
"drizzle" => "homebrew/boneyard",
"drush" => "homebrew/php",
"dsniff" => "homebrew/boneyard",
"dupx" => "homebrew/boneyard",
"dwm" => "homebrew/x11",
"dzen2" => "homebrew/x11",
"easy-tag" => "homebrew/x11",
"echoping" => "homebrew/boneyard",
"electric-fence" => "homebrew/boneyard",
"encfs" => "homebrew/fuse",
"ext2fuse" => "homebrew/fuse",
"ext4fuse" => "homebrew/fuse",
"fceux" => "homebrew/games",
"feh" => "homebrew/x11",
"ffts" => "homebrew/boneyard",
"figtoipe" => "homebrew/head-only",
"fox" => "homebrew/x11",
"freeglut" => "homebrew/x11",
"freerdp" => "homebrew/x11",
"fsv" => "homebrew/boneyard",
"fuse-zip" => "homebrew/fuse",
"fuse4x" => "homebrew/fuse",
"fuse4x-kext" => "homebrew/fuse",
"gant" => "homebrew/boneyard",
"gcsfuse" => "homebrew/fuse",
"gdrive" => "homebrew/boneyard",
"geda-gaf" => "homebrew/x11",
"geeqie" => "homebrew/x11",
"geomview" => "homebrew/x11",
"gerbv" => "homebrew/x11",
"ggobi" => "homebrew/x11",
"giblib" => "homebrew/x11",
"git-encrypt" => "homebrew/boneyard",
"git-flow-clone" => "homebrew/boneyard",
"git-latexdiff" => "homebrew/tex",
"gitfs" => "homebrew/fuse",
"glade" => "homebrew/x11",
"gle" => "homebrew/x11",
"gnumeric" => "homebrew/x11",
"gnunet" => "homebrew/boneyard",
"gobby" => "homebrew/x11",
"googlecl" => "homebrew/boneyard",
"gpredict" => "homebrew/x11",
"gptfdisk" => "homebrew/boneyard",
"grace" => "homebrew/x11",
"grads" => "homebrew/binary",
"graylog2-server" => "homebrew/boneyard",
"gromacs" => "homebrew/science",
"gsmartcontrol" => "homebrew/x11",
"gtk-chtheme" => "homebrew/x11",
"gtkglarea" => "homebrew/boneyard",
"gtksourceviewmm" => "homebrew/x11",
"gtksourceviewmm3" => "homebrew/x11",
"gtkwave" => "homebrew/x11",
"guilt" => "homebrew/boneyard",
"gv" => "homebrew/x11",
"hatari" => "homebrew/x11",
"helios" => "spotify/public",
"hexchat" => "homebrew/x11",
"hllib" => "homebrew/boneyard",
"honeyd" => "homebrew/boneyard",
"hugs98" => "homebrew/boneyard",
"hwloc" => "homebrew/science",
"ifuse" => "homebrew/fuse",
"imake" => "homebrew/x11",
"inkscape" => "homebrew/x11",
"iojs" => "homebrew/versions",
"ipe" => "homebrew/boneyard",
"ipopt" => "homebrew/science",
"iptux" => "homebrew/x11",
"itsol" => "homebrew/science",
"iulib" => "homebrew/boneyard",
"jscoverage" => "homebrew/boneyard",
"jsl" => "homebrew/binary",
"jstalk" => "homebrew/boneyard",
"justniffer" => "homebrew/boneyard",
"kbtin" => "homebrew/boneyard",
"kerl" => "homebrew/head-only",
"kernagic" => "homebrew/x11",
"kismet" => "homebrew/boneyard",
"klavaro" => "homebrew/x11",
"kumofs" => "homebrew/boneyard",
"latex-mk" => "homebrew/tex",
"libdlna" => "homebrew/boneyard",
"libgtextutils" => "homebrew/science",
"libqxt" => "homebrew/boneyard",
"librets" => "homebrew/boneyard",
"libspotify" => "homebrew/binary",
"lilypond" => "homebrew/tex",
"lmutil" => "homebrew/binary",
"magit" => "homebrew/emacs",
"meld" => "homebrew/x11",
"mesalib-glw" => "homebrew/x11",
"mess" => "homebrew/games",
"metalua" => "homebrew/boneyard",
"mit-scheme" => "homebrew/x11",
"mlkit" => "homebrew/boneyard",
"mlton" => "homebrew/boneyard",
"morse" => "homebrew/x11",
"mp3fs" => "homebrew/fuse",
"mpio" => "homebrew/boneyard",
"mscgen" => "homebrew/x11",
"msgpack-rpc" => "homebrew/boneyard",
"mupdf" => "homebrew/x11",
"mysql-connector-odbc" => "homebrew/boneyard",
"mysql-proxy" => "homebrew/boneyard",
"mysqlreport" => "homebrew/boneyard",
"net6" => "homebrew/boneyard",
"newick-utils" => "homebrew/science",
"nlopt" => "homebrew/science",
"ntfs-3g" => "homebrew/fuse",
"octave" => "homebrew/science",
"opencv" => "homebrew/science",
"openfst" => "homebrew/science",
"opengrm-ngram" => "homebrew/science",
"ori" => "homebrew/fuse",
"p11-kit" => "homebrew/boneyard",
"pan" => "homebrew/boneyard",
"paq8px" => "homebrew/boneyard",
"par2tbb" => "homebrew/boneyard",
"pari" => "homebrew/x11",
"pathfinder" => "homebrew/boneyard",
"pcb" => "homebrew/x11",
"pdf-tools" => "homebrew/emacs",
"pdf2image" => "homebrew/x11",
"pdfjam" => "homebrew/tex",
"pdftoipe" => "homebrew/head-only",
"pebble-sdk" => "pebble/pebble-sdk",
"pgplot" => "homebrew/x11",
"pixie" => "homebrew/x11",
"pjsip" => "homebrew/boneyard",
"pocl" => "homebrew/science",
"pplatex" => "homebrew/tex",
"prooftree" => "homebrew/x11",
"pulse" => "homebrew/boneyard",
"pyenv-pip-rehash" => "homebrew/boneyard",
"pyxplot" => "homebrew/x11",
"qfits" => "homebrew/boneyard",
"qi" => "homebrew/boneyard",
"qiv" => "homebrew/boneyard",
"qrupdate" => "homebrew/science",
"rdesktop" => "homebrew/x11",
"rocket" => "homebrew/boneyard",
"rofs-filtered" => "homebrew/fuse",
"rxvt-unicode" => "homebrew/x11",
"s3-backer" => "homebrew/fuse",
"s3fs" => "homebrew/fuse",
"salt" => "homebrew/science",
"scantailor" => "homebrew/x11",
"sdelta3" => "homebrew/boneyard",
"sedna" => "homebrew/boneyard",
"shark" => "homebrew/science",
"shell.fm" => "homebrew/boneyard",
"simple-mtpfs" => "homebrew/fuse",
"sitecopy" => "homebrew/boneyard",
"slicot" => "homebrew/science",
"smartsim" => "homebrew/x11",
"solfege" => "homebrew/boneyard",
"sptk" => "homebrew/x11",
"sshfs" => "homebrew/fuse",
"stormfs" => "homebrew/fuse",
"sundials" => "homebrew/science",
"swi-prolog" => "homebrew/x11",
"sxiv" => "homebrew/x11",
"sylpheed" => "homebrew/x11",
"syslog-ng" => "homebrew/boneyard",
"tabbed" => "homebrew/x11",
"terminator" => "homebrew/x11",
"tetgen" => "homebrew/science",
"texmacs" => "homebrew/boneyard",
"texwrapper" => "homebrew/tex",
"ticcutils" => "homebrew/science",
"tiger-vnc" => "homebrew/x11",
"timbl" => "homebrew/science",
"tmap" => "homebrew/boneyard",
"transmission-remote-gtk" => "homebrew/x11",
"tup" => "homebrew/fuse",
"uim" => "homebrew/x11",
"ume" => "homebrew/games",
"upnp-router-control" => "homebrew/x11",
"urweb" => "homebrew/boneyard",
"ushare" => "homebrew/boneyard",
"viewglob" => "homebrew/boneyard",
"vobcopy" => "homebrew/boneyard",
"wdfs" => "homebrew/fuse",
"whereami" => "homebrew/boneyard",
"wkhtmltopdf" => "homebrew/boneyard",
"wmctrl" => "homebrew/x11",
"wopr" => "homebrew/science",
"wps2odt" => "homebrew/boneyard",
"x3270" => "homebrew/x11",
"xar" => "homebrew/dupes",
"xastir" => "homebrew/x11",
"xchat" => "homebrew/x11",
"xclip" => "homebrew/x11",
"xdotool" => "homebrew/x11",
"xdu" => "homebrew/x11",
"xmount" => "homebrew/fuse",
"xournal" => "homebrew/x11",
"xpa" => "homebrew/x11",
"xpdf" => "homebrew/x11",
"xplot" => "homebrew/x11",
"xspringies" => "homebrew/x11",
"yarp" => "homebrew/x11",
"ydict" => "homebrew/boneyard",
"zenity" => "homebrew/x11",
}
|
# frozen_string_literal: true
require "net/http"
require "json"
module RepologyParser
def call_api(url)
ohai "- Calling API #{url}" if Homebrew.args.verbose?
uri = URI(url)
response = Net::HTTP.get(uri)
ohai "Parsing response" if Homebrew.args.verbose?
JSON.parse(response)
end
def query_repology_api(last_package_in_response = "")
url = "https://repology.org/api/v1/projects/#{last_package_in_response}?inrepo=homebrew&outdated=1"
call_api(url)
end
def parse_repology_api
ohai "Querying outdated packages from Repology"
page_no = 1
ohai "\n- Paginating repology api page: #{page_no}"
outdated_packages = query_repology_api("")
last_package_index = outdated_packages.size - 1
response_size = outdated_packages.size
while response_size > 1
page_no += 1
ohai "\n- Paginating repology api page: #{page_no}"
last_package_in_response = outdated_packages.keys[last_package_index]
response = query_repology_api("#{last_package_in_response}/")
response_size = response.size
outdated_packages.merge!(response)
last_package_index = outdated_packages.size - 1
end
ohai "\n- #{outdated_packages.size} outdated packages identified"
outdated_packages
end
def validate__repology_packages(outdated_repology_packages)
ohai "\n- Verify Outdated Repology Packages as Homebrew Formulae"
packages = {}
outdated_repology_packages.each do |_name, repositories|
# identify homebrew repo
repology_homebrew_repo = repositories.find do |repo|
repo["repo"] == "homebrew"
end
next if repology_homebrew_repo.empty?
latest_version = nil
# identify latest version amongst repology repos
repositories.each do |repo|
latest_version = repo["version"] if repo["status"] == "newest"
end
packages[repology_homebrew_repo["srcname"]] = {
"repology_latest_version" => latest_version,
}
end
# hash of hashes {'openclonk' => {repology_latest_version => 7.0}, ..}
packages
end
end
guard against infinite loop when querying repology
# frozen_string_literal: true
require "net/http"
require "json"
module RepologyParser
def call_api(url)
ohai "- Calling API #{url}" if Homebrew.args.verbose?
uri = URI(url)
response = Net::HTTP.get(uri)
ohai "Parsing response" if Homebrew.args.verbose?
JSON.parse(response)
end
def query_repology_api(last_package_in_response = "")
url = "https://repology.org/api/v1/projects/#{last_package_in_response}?inrepo=homebrew&outdated=1"
call_api(url)
end
def parse_repology_api
ohai "Querying outdated packages from Repology"
page_no = 1
ohai "\n- Paginating repology api page: #{page_no}"
outdated_packages = query_repology_api("")
last_package_index = outdated_packages.size - 1
response_size = outdated_packages.size
while response_size > 1 && page_no <= 15
page_no += 1
ohai "\n- Paginating repology api page: #{page_no}"
last_package_in_response = outdated_packages.keys[last_package_index]
response = query_repology_api("#{last_package_in_response}/")
response_size = response.size
outdated_packages.merge!(response)
last_package_index = outdated_packages.size - 1
end
ohai "\n- #{outdated_packages.size} outdated packages identified"
outdated_packages
end
def validate__repology_packages(outdated_repology_packages)
ohai "\n- Verify Outdated Repology Packages as Homebrew Formulae"
packages = {}
outdated_repology_packages.each do |_name, repositories|
# identify homebrew repo
repology_homebrew_repo = repositories.find do |repo|
repo["repo"] == "homebrew"
end
next if repology_homebrew_repo.empty?
latest_version = nil
# identify latest version amongst repology repos
repositories.each do |repo|
latest_version = repo["version"] if repo["status"] == "newest"
end
packages[repology_homebrew_repo["srcname"]] = {
"repology_latest_version" => latest_version,
}
end
# hash of hashes {'openclonk' => {repology_latest_version => 7.0}, ..}
packages
end
end
|
bash "Deploy Meteor" do
user "root"
code <<-EOF
cd /srv/www/skyveri_main_site/current/
rm -rf ./bundle
rm -rf tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
mrt install
meteor bundle tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
tar -xzf tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
rm tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
echo "process.env.MONGO_URL = 'mongodb://skyveri_readonly:Feiun5s09@oceanic.mongohq.com:10016/skyveri_main'; process.env.PORT = 80; require('./bundle/main.js'); " > server.js
chown deploy:www-data /srv/www/skyveri_main_site/current/server.js
chown -R deploy:www-data /srv/www/skyveri_main_site/current/bundle
monit restart node_web_app_skyveri_main_site
EOF
end
Update deploy.rb
bash "Deploy Meteor" do
user "root"
code <<-EOF
cd /srv/www/skyveri_main_site/current/
rm -rf ./bundle
rm -rf tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
mrt install
meteor bundle tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
tar -xzf tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
rm tmp_f90e9fkjkjf0s0esre0r9034932952359sfd90.tgz
echo "process.env.MONGO_URL = 'mongodb://skyveri_readonly:Feiun5s09@oceanic.mongohq.com:10016/skyveri_main'; process.env.PORT = 80; require('./bundle/main.js'); " > server.js
chown deploy:www-data /srv/www/skyveri_main_site/current/server.js
chown -R deploy:www-data /srv/www/skyveri_main_site/current/bundle
monit restart node_web_app_skyveri_main_site
EOF
end
|
require 'dogapi'
require 'time'
require 'test_base.rb'
class TestClient < Test::Unit::TestCase
include TestBase
def test_tags
hostname = "test.tag.host.#{random}"
dog = Dogapi::Client.new(@api_key, @app_key)
# post a metric to make sure the test host context exists
dog.emit_point('test.tag.metric', 1, :host => hostname)
# Disable this call until we fix the timeouts
# dog.all_tags()
sleep 3
dog.detach_tags(hostname)
code, resp = dog.host_tags(hostname)
assert resp["tags"].size == 0
dog.add_tags(hostname, ['test.tag.1', 'test.tag.2'])
code, resp = dog.host_tags(hostname)
new_tags = resp["tags"]
assert new_tags.size == 2
assert new_tags.include?('test.tag.1')
assert new_tags.include?('test.tag.2')
dog.add_tags(hostname, ['test.tag.3'])
code, resp = dog.host_tags(hostname)
new_tags = resp["tags"]
assert new_tags.size == 3
assert new_tags.include?('test.tag.1')
assert new_tags.include?('test.tag.2')
assert new_tags.include?('test.tag.3')
dog.update_tags(hostname, ['test.tag.4'])
code, resp = dog.host_tags(hostname)
new_tags = resp["tags"]
assert new_tags.size == 1
assert new_tags.include?('test.tag.4')
dog.detach_tags(hostname)
code, resp = dog.host_tags(hostname)
assert resp["tags"].size == 0
end
def test_events
now = Time.now()
tags = ["test-run:#{random}"]
now_ts = now
now_title = 'dogapi-rb end test title ' + now_ts.to_i.to_s
now_message = 'test message ' + now_ts.to_i.to_s
before_ts = (now - 5*60)
before_title = 'dogapi-rb start test title ' + before_ts.to_i.to_s
before_message = 'test message ' + before_ts.to_i.to_s
dog = Dogapi::Client.new(@api_key, @app_key)
dog_r = Dogapi::Client.new(@api_key)
# Tag the events with the build number, because traivs
e1 = Dogapi::Event.new(now_message, :msg_title =>now_title, :date_happened => now_ts, :tags => tags)
e2 = Dogapi::Event.new(before_message, :msg_title =>before_title,
:date_happened => before_ts, :tags => tags)
code, resp = dog_r.emit_event(e1)
now_event_id = resp["event"]["id"]
code, resp = dog_r.emit_event(e2)
before_event_id = resp["event"]["id"]
sleep 3
code, resp = dog.stream(before_ts, now_ts + 1, :tags => tags)
stream = resp["events"]
assert_equal 2, stream.length()
assert_equal stream.last['title'], before_title
assert_equal stream.first['title'], now_title
code, resp = dog.get_event(now_event_id)
now_event = resp['event']
code, resp = dog.get_event(before_event_id)
before_event = resp['event']
assert now_event['text'] == now_message
assert before_event['text'] == before_message
# Testing priorities
code, resp = dog_r.emit_event(Dogapi::Event.new(now_message, :msg_title =>now_title, :date_happened => now_ts, :priority => "low"))
low_event_id = resp["event"]["id"]
sleep 3
code, resp = dog.get_event(low_event_id)
low_event = resp['event']
assert low_event['priority'] == "low"
# Testing aggregates
agg_ts = Time.now()
code, resp = dog_r.emit_event(Dogapi::Event.new("Testing Aggregation (first)", :aggregation_key => now_ts.to_i))
first = resp["event"]["id"]
code, resp = dog_r.emit_event(Dogapi::Event.new("Testing Aggregation (second)", :aggregation_key => now_ts.to_i))
second = resp["event"]["id"]
sleep 3
code, resp = dog.get_event(first)
agg1 = resp["event"]
code, resp = dog.get_event(second)
agg2 = resp["event"]
# FIXME Need to export is_aggregate/children fields
end
def test_metrics
# FIXME: actually verify this once there's a way to look at metrics through the api
dog = Dogapi::Client.new(@api_key, @app_key)
dog_r = Dogapi::Client.new(@api_key)
dog_r.emit_point('test.metric.metric', 10, :host => 'test.metric.host')
dog_r.emit_points('test.metric.metric', [[Time.now-5*60, 0]], :host => 'test.metric.host')
dog_r.emit_points('test.metric.metric', [[Time.now-60, 20], [Time.now-30, 10], [Time.now, 5]], :tags => ["test:tag.1", "test:tag2"])
end
end
Adds the job_number to make a test run unique
It doesn't make a lot of sense to measure the length of the event stream as a test
require 'dogapi'
require 'time'
require 'test_base.rb'
class TestClient < Test::Unit::TestCase
include TestBase
def test_tags
hostname = "test.tag.host.#{job_number}"
dog = Dogapi::Client.new(@api_key, @app_key)
# post a metric to make sure the test host context exists
dog.emit_point('test.tag.metric', 1, :host => hostname)
# Disable this call until we fix the timeouts
# dog.all_tags()
sleep 3
dog.detach_tags(hostname)
code, resp = dog.host_tags(hostname)
assert resp["tags"].size == 0
dog.add_tags(hostname, ['test.tag.1', 'test.tag.2'])
code, resp = dog.host_tags(hostname)
new_tags = resp["tags"]
assert new_tags.size == 2
assert new_tags.include?('test.tag.1')
assert new_tags.include?('test.tag.2')
dog.add_tags(hostname, ['test.tag.3'])
code, resp = dog.host_tags(hostname)
new_tags = resp["tags"]
assert new_tags.size == 3
assert new_tags.include?('test.tag.1')
assert new_tags.include?('test.tag.2')
assert new_tags.include?('test.tag.3')
dog.update_tags(hostname, ['test.tag.4'])
code, resp = dog.host_tags(hostname)
new_tags = resp["tags"]
assert new_tags.size == 1
assert new_tags.include?('test.tag.4')
dog.detach_tags(hostname)
code, resp = dog.host_tags(hostname)
assert resp["tags"].size == 0
end
def test_events
now = Time.now()
# Tag the events with the build number, because Travis parallel testing
# can cause problems with the event stream
tags = ["test-run:#{job_number}"]
now_ts = now
now_title = 'dogapi-rb end test title ' + now_ts.to_i.to_s
now_message = 'test message ' + now_ts.to_i.to_s
before_ts = (now - 5*60)
before_title = 'dogapi-rb start test title ' + before_ts.to_i.to_s
before_message = 'test message ' + before_ts.to_i.to_s
dog = Dogapi::Client.new(@api_key, @app_key)
dog_r = Dogapi::Client.new(@api_key)
# Tag the events with the build number, because traivs
e1 = Dogapi::Event.new(now_message, :msg_title =>now_title, :date_happened => now_ts, :tags => tags)
e2 = Dogapi::Event.new(before_message, :msg_title =>before_title,
:date_happened => before_ts, :tags => tags)
code, resp = dog_r.emit_event(e1)
now_event_id = resp["event"]["id"]
code, resp = dog_r.emit_event(e2)
before_event_id = resp["event"]["id"]
sleep 3
code, resp = dog.stream(before_ts, now_ts + 1, :tags => tags)
stream = resp["events"]
assert_equal stream.last['title'], before_title
assert_equal stream.first['title'], now_title
code, resp = dog.get_event(now_event_id)
now_event = resp['event']
code, resp = dog.get_event(before_event_id)
before_event = resp['event']
assert now_event['text'] == now_message
assert before_event['text'] == before_message
# Testing priorities
code, resp = dog_r.emit_event(Dogapi::Event.new(now_message, :msg_title =>now_title, :date_happened => now_ts, :priority => "low"))
low_event_id = resp["event"]["id"]
sleep 3
code, resp = dog.get_event(low_event_id)
low_event = resp['event']
assert low_event['priority'] == "low"
# Testing aggregates
agg_ts = Time.now()
code, resp = dog_r.emit_event(Dogapi::Event.new("Testing Aggregation (first)", :aggregation_key => now_ts.to_i))
first = resp["event"]["id"]
code, resp = dog_r.emit_event(Dogapi::Event.new("Testing Aggregation (second)", :aggregation_key => now_ts.to_i))
second = resp["event"]["id"]
sleep 3
code, resp = dog.get_event(first)
agg1 = resp["event"]
code, resp = dog.get_event(second)
agg2 = resp["event"]
# FIXME Need to export is_aggregate/children fields
end
def test_metrics
# FIXME: actually verify this once there's a way to look at metrics through the api
dog = Dogapi::Client.new(@api_key, @app_key)
dog_r = Dogapi::Client.new(@api_key)
dog_r.emit_point('test.metric.metric', 10, :host => 'test.metric.host')
dog_r.emit_points('test.metric.metric', [[Time.now-5*60, 0]], :host => 'test.metric.host')
dog_r.emit_points('test.metric.metric', [[Time.now-60, 20], [Time.now-30, 10], [Time.now, 5]], :tags => ["test:tag.1", "test:tag2"])
end
end
|
require 'dogapi'
require 'time'
require 'test_base.rb'
class TestDashes < Test::Unit::TestCase
include TestBase
def test_dashes
dog = Dogapi::Client.new(@api_key, @app_key)
# Create a dashboard.
title = "foobar-#{job_number}"
description = 'desc'
graphs = [{
"definition" => {
"events" => [],
"requests" => [
{"q" => "avg:system.mem.free{*}"}
],
"viz" => "timeseries"
},
"title" => "Average Memory Free"
}]
status, dash_response = dog.create_dashboard(title, description, graphs)
assert_equal "200", status, "Creation failed, response: #{dash_response}"
dash_id = dash_response["dash"]["id"]
# Fetch the dashboard and assert all is well.
status, dash_response = dog.get_dashboard(dash_id)
assert_equal "200", status, "Fetch failed, response: #{dash_response}"
dash = dash_response["dash"]
assert_equal title, dash["title"]
assert_equal description, dash["description"]
assert_equal graphs, dash["graphs"]
# Update the dashboard.
title = "blahfoobar-#{job_number}"
description = 'asdfdesc'
graphs = [{
"definition" => {
"events" => [],
"requests" => [
{"q" => "sum:system.mem.free{*}"}
],
"viz" => "timeseries"
},
"title" => "Sum Memory Free"
}]
status, dash_response = dog.update_dashboard(dash_id, title, description, graphs)
assert_equal "200", status, "Updated failed, response: #{dash_response}"
# Fetch the dashboard and assert all is well.
status, dash_response = dog.get_dashboard(dash_id)
assert_equal "200", status, "Fetch failed, response: #{dash_response}"
dash = dash_response["dash"]
assert_equal title, dash["title"]
assert_equal description, dash["description"]
assert_equal graphs, dash["graphs"]
# Fetch all the dashboards.
status, dash_response = dog.get_dashboards()
assert_equal "200", status, "fetch failed, response: #{dash_response}"
dashes = dash_response["dashes"]
assert dashes.length
dash = dashes.sort{|x,y| x["id"] <=> y["id"]}.last
assert_equal title, dash["title"]
assert_equal dash_id.to_s, dash["id"]
# Delete the dashboard.
status, dash_response = dog.delete_dashboard(dash_id)
assert_equal "204", status, "Deleted failed, response: #{dash_response}"
# Fetch the dashboard and assert all it's gone.
status, dash_response = dog.get_dashboard(dash_id)
assert_equal "404", status, "Still there failed, response: #{dash_response}"
end
end
don't assert about positional details in dashboards
require 'dogapi'
require 'time'
require 'test_base.rb'
class TestDashes < Test::Unit::TestCase
include TestBase
def test_dashes
dog = Dogapi::Client.new(@api_key, @app_key)
# Create a dashboard.
title = "foobar-#{job_number}"
description = 'desc'
graphs = [{
"definition" => {
"events" => [],
"requests" => [
{"q" => "avg:system.mem.free{*}"}
],
"viz" => "timeseries"
},
"title" => "Average Memory Free"
}]
status, dash_response = dog.create_dashboard(title, description, graphs)
assert_equal "200", status, "Creation failed, response: #{dash_response}"
dash_id = dash_response["dash"]["id"]
# Fetch the dashboard and assert all is well.
status, dash_response = dog.get_dashboard(dash_id)
assert_equal "200", status, "Fetch failed, response: #{dash_response}"
dash = dash_response["dash"]
assert_equal title, dash["title"]
assert_equal description, dash["description"]
assert_equal graphs, dash["graphs"]
# Update the dashboard.
title = "blahfoobar-#{job_number}"
description = 'asdfdesc'
graphs = [{
"definition" => {
"events" => [],
"requests" => [
{"q" => "sum:system.mem.free{*}"}
],
"viz" => "timeseries"
},
"title" => "Sum Memory Free"
}]
status, dash_response = dog.update_dashboard(dash_id, title, description, graphs)
assert_equal "200", status, "Updated failed, response: #{dash_response}"
# Fetch the dashboard and assert all is well.
status, dash_response = dog.get_dashboard(dash_id)
assert_equal "200", status, "Fetch failed, response: #{dash_response}"
dash = dash_response["dash"]
assert_equal title, dash["title"]
assert_equal description, dash["description"]
assert_equal graphs, dash["graphs"]
# Fetch all the dashboards, assert our created one is in the list of all
status, dash_response = dog.get_dashboards()
assert_equal "200", status, "fetch failed, response: #{dash_response}"
dashes = dash_response["dashes"]
assert dashes.any? { |d| title == d["title"] }
dash = dashes.find { |d| title == d["title"] }
assert_equal title, dash["title"]
assert_equal dash_id.to_s, dash["id"]
# Delete the dashboard.
status, dash_response = dog.delete_dashboard(dash_id)
assert_equal "204", status, "Deleted failed, response: #{dash_response}"
# Fetch the dashboard and assert all it's gone.
status, dash_response = dog.get_dashboard(dash_id)
assert_equal "404", status, "Still there failed, response: #{dash_response}"
end
end
|
class Formatters::Annotate
include Formatters::FormatterHelpers
def initialize(base = nil, options = {}, &block)
@base = base || ENV["TM_PROJECT_DIRECTORY"]
@header = options[:header] || "Annotate / Blame"
layout(&block) if block_given?
end
def layout(&block)
puts <<-EOF
<html>
<head>
<title>#{@header}</title>
<link type="text/css" rel="stylesheet" media="screen" href="#{resource_url('style.css')}"/>
</head>
<body id='body'>
EOF
yield self
puts <<-EOF
</body>
<script type='text/javascript' src="#{resource_url('prototype.js')}"></script>
<script type='text/javascript' src="#{resource_url('rb_gateway.js')}"></script>
<script language='JavaScript'>
function show_revision(revision)
{
$('body').update(gateway_command('annotate.rb', [revision]));
}
</script>
</html>
EOF
end
def header(text)
puts "<h2>#{text}</h2>"
end
def make_non_breaking(output)
htmlize(output.to_s.strip).gsub(" ", " ")
end
def options_for_select(select_options = [], selected_value = nil)
output = ""
select_options.each do |name, val|
selected = (val == selected_value) ? "selected='true'" : ""
output << "<option value='#{val}' #{selected}>#{htmlize(name)}</option>"
end
output
end
def select_box(name, select_options = [], options = {})
options[:name] ||= name
options[:id] ||= name
# puts select_options.inspect
<<-EOF
Revision<br/>
<select name='#{options[:name]}' id='#{options[:id]}' onchange="#{options[:onchange]}" style='width:100%'>
#{select_options}
</select>
EOF
end
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1
return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds
case distance_in_seconds
when 0..4 then 'less than 5 seconds'
when 5..9 then 'less than 10 seconds'
when 10..19 then 'less than 20 seconds'
when 20..39 then 'half a minute'
when 40..59 then 'less than a minute'
else '1 minute'
end
when 2..44 then "#{distance_in_minutes} minutes"
when 45..89 then 'about 1 hour'
when 90..1439 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
when 1440..2879 then '1 day'
when 2880..43199 then "#{(distance_in_minutes / 1440).round} days"
when 43200..86399 then 'about 1 month'
when 86400..525599 then "#{(distance_in_minutes / 43200).round} months"
when 525600..1051199 then 'about 1 year'
else "over #{(distance_in_minutes / 525600).round} years"
end
end
def friendly_date(date)
return date if date.is_a?(String)
distance_of_time_in_words(Time.now, date)
end
def content(annotations, log_entries = nil, selected_revision = nil)
if log_entries
formatted_options = [["current", ""]] + log_entries.map{|le| ["#{short_rev(le[:rev])} - #{le[:author]} - #{friendly_date(le[:date])} - #{le[:msg].split("\n").first}", short_rev(le[:rev])] }
puts select_box(
"rev",
options_for_select(formatted_options, selected_revision),
:onchange => "show_revision($F(this))"
)
end
# puts annotations.inspect
puts '<code>'
puts <<-EOF
<table class='codediff inline'>
<thead>
<tr>
<td class='line-numbers'>revision</td>
<td class='line-numbers'>author</td>
<td class='line-numbers'>date</td>
<td class='line-numbers'>line</td>
<td/>
</tr>
</thead>
<tbody>
EOF
last_formatted_line = {}
annotations.each do |annotation|
col_class = []
col_class << "selected" if ENV["TM_LINE_NUMBER"].to_i == annotation[:ln].to_i
col_class << "ins" if annotation[:rev] == "-current-"
col_class = col_class * " "
formatted_line = {
:rev => annotation[:rev],
:author => annotation[:author],
:date => friendly_date(annotation[:date]),
:ln => annotation[:ln],
:text => annotation[:text]
}
display = formatted_line.dup
[:rev, :author, :date].each { |k| display[k] = "…" } if display[:rev]==last_formatted_line[:rev]
puts <<-EOF
<tr>
<td class="line-numbers"><a href='javascript:show_revision("#{display[:rev]}"); return false;'>#{make_non_breaking display[:rev]}</a></td>
<td class="line-numbers">#{make_non_breaking display[:author]}</td>
<td class="line-numbers">#{make_non_breaking display[:date]}</td>
<td class="line-numbers">#{make_non_breaking display[:ln]}</td>
<td class="code #{col_class}">#{htmlize(display[:text])}</td>
</tr>
EOF
last_formatted_line = formatted_line
end
puts <<-EOF
</tbody>
</table>
EOF
puts '</code>'
end
end
module FriendlyTime
def to_friendly(time=true)
time=false if Date==self.class
ret_val = if time
strftime "%b %d, %Y %I:%M %p" + (time=="zone"? " %Z" : "")
else
strftime "%b %d, %Y"
end
ret_val.gsub(" 0", " ")
end
end
class Time
include FriendlyTime
end
class Date
include FriendlyTime
end
class DateTime
include FriendlyTime
end
keyboard accelerators to browse annotations (n and p)
class Formatters::Annotate
include Formatters::FormatterHelpers
def initialize(base = nil, options = {}, &block)
@base = base || ENV["TM_PROJECT_DIRECTORY"]
@header = options[:header] || "Annotate / Blame"
layout(&block) if block_given?
end
def layout(&block)
puts <<-EOF
<html>
<head>
<title>#{@header}</title>
<link type="text/css" rel="stylesheet" media="screen" href="#{resource_url('style.css')}"/>
</head>
<body id='body'>
<div id='debug'></div>
<div id='content'>
EOF
yield self
puts <<-EOF
</div>
</body>
<script type='text/javascript' src="#{resource_url('prototype.js')}"></script>
<script type='text/javascript' src="#{resource_url('rb_gateway.js')}"></script>
<script language='JavaScript'>
function show_revision(revision)
{
$('content').update(gateway_command('annotate.rb', [revision]));
}
function keypress_listener(e)
{
// if (e.keyCode==Event.KEY_LEFT)
// $('debug').update('escape!!!');
// else
// $('debug').update(e.keyCode)
switch(e.keyCode) {
case 110: // n
if ($('rev').selectedIndex >= 1)
{
$('rev').selectedIndex = $('rev').selectedIndex - 1
$('rev').onchange();
}
break;
case 112: // p
if ($('rev').selectedIndex < $('rev').options.length - 1)
{
$('rev').selectedIndex = $('rev').selectedIndex + 1
$('rev').onchange();
}
break;
}
}
try {
Event.observe(document, "keypress", keypress_listener.bindAsEventListener());
}
catch (e) {
$('debug').update(e)
}
</script>
</html>
EOF
end
def header(text)
puts "<h2>#{text}</h2>"
end
def make_non_breaking(output)
htmlize(output.to_s.strip).gsub(" ", " ")
end
def options_for_select(select_options = [], selected_value = nil)
output = ""
select_options.each do |name, val|
selected = (val == selected_value) ? "selected='true'" : ""
output << "<option value='#{val}' #{selected}>#{htmlize(name)}</option>"
end
output
end
def select_box(name, select_options = [], options = {})
options[:name] ||= name
options[:id] ||= name
# puts select_options.inspect
<<-EOF
Revision<br/>
<select name='#{options[:name]}' id='#{options[:id]}' onchange="#{options[:onchange]}" style='width:100%'>
#{select_options}
</select>
EOF
end
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round
case distance_in_minutes
when 0..1
return (distance_in_minutes == 0) ? 'less than a minute' : '1 minute' unless include_seconds
case distance_in_seconds
when 0..4 then 'less than 5 seconds'
when 5..9 then 'less than 10 seconds'
when 10..19 then 'less than 20 seconds'
when 20..39 then 'half a minute'
when 40..59 then 'less than a minute'
else '1 minute'
end
when 2..44 then "#{distance_in_minutes} minutes"
when 45..89 then 'about 1 hour'
when 90..1439 then "about #{(distance_in_minutes.to_f / 60.0).round} hours"
when 1440..2879 then '1 day'
when 2880..43199 then "#{(distance_in_minutes / 1440).round} days"
when 43200..86399 then 'about 1 month'
when 86400..525599 then "#{(distance_in_minutes / 43200).round} months"
when 525600..1051199 then 'about 1 year'
else "over #{(distance_in_minutes / 525600).round} years"
end
end
def friendly_date(date)
return date if date.is_a?(String)
distance_of_time_in_words(Time.now, date)
end
def content(annotations, log_entries = nil, selected_revision = nil)
if log_entries
formatted_options = [["current", ""]] + log_entries.map{|le| ["#{short_rev(le[:rev])} - #{le[:author]} - #{friendly_date(le[:date])} - #{le[:msg].split("\n").first}", short_rev(le[:rev])] }
puts select_box(
"rev",
options_for_select(formatted_options, selected_revision),
:onchange => "show_revision($F(this))"
)
end
# puts annotations.inspect
puts '<code>'
puts <<-EOF
<table class='codediff inline'>
<thead>
<tr>
<td class='line-numbers'>revision</td>
<td class='line-numbers'>author</td>
<td class='line-numbers'>date</td>
<td class='line-numbers'>line</td>
<td/>
</tr>
</thead>
<tbody>
EOF
last_formatted_line = {}
annotations.each do |annotation|
col_class = []
col_class << "selected" if ENV["TM_LINE_NUMBER"].to_i == annotation[:ln].to_i
col_class << "ins" if annotation[:rev] == "-current-"
col_class = col_class * " "
formatted_line = {
:rev => annotation[:rev],
:author => annotation[:author],
:date => friendly_date(annotation[:date]),
:ln => annotation[:ln],
:text => annotation[:text]
}
display = formatted_line.dup
[:rev, :author, :date].each { |k| display[k] = "…" } if display[:rev]==last_formatted_line[:rev]
puts <<-EOF
<tr>
<td class="line-numbers"><a href='javascript:show_revision("#{display[:rev]}"); return false;'>#{make_non_breaking display[:rev]}</a></td>
<td class="line-numbers">#{make_non_breaking display[:author]}</td>
<td class="line-numbers">#{make_non_breaking display[:date]}</td>
<td class="line-numbers">#{make_non_breaking display[:ln]}</td>
<td class="code #{col_class}">#{htmlize(display[:text])}</td>
</tr>
EOF
last_formatted_line = formatted_line
end
puts <<-EOF
</tbody>
</table>
EOF
puts '</code>'
end
end
module FriendlyTime
def to_friendly(time=true)
time=false if Date==self.class
ret_val = if time
strftime "%b %d, %Y %I:%M %p" + (time=="zone"? " %Z" : "")
else
strftime "%b %d, %Y"
end
ret_val.gsub(" 0", " ")
end
end
class Time
include FriendlyTime
end
class Date
include FriendlyTime
end
class DateTime
include FriendlyTime
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'time_rounder/version'
Gem::Specification.new do |spec|
spec.name = 'time_rounder'
spec.version = TimeRounder::VERSION
spec.authors = ['Ryan Condron']
spec.email = ['rebelwebdevelopment@gmail.com']
spec.summary = 'Round time with ease'
spec.description = 'Round time using logic and not complex math.'
spec.homepage = 'https://github.com/rebelweb/time_rounder'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency 'bundler', '~> 1.10'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'minitest'
end
added benchmarking gems
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'time_rounder/version'
Gem::Specification.new do |spec|
spec.name = 'time_rounder'
spec.version = TimeRounder::VERSION
spec.authors = ['Ryan Condron']
spec.email = ['rebelwebdevelopment@gmail.com']
spec.summary = 'Round time with ease'
spec.description = 'Round time using logic and not complex math.'
spec.homepage = 'https://github.com/rebelweb/time_rounder'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = 'exe'
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency 'bundler', '~> 1.10'
spec.add_development_dependency 'rake', '~> 10.0'
spec.add_development_dependency 'minitest'
spec.add_development_dependency 'benchmark-ips'
spec.add_development_dependency 'stackprof'
end
|
require 'rake/clean'
CLOBBER.include("out/#{PRG}.js")
CLEAN.include('gen/top-summary.md')
tool_doc_top = "#{File.dirname(__FILE__)}/doc-top"
task :default => "out/#{PRG}.js"
@coffeeGen ||= []
@deps.push('gen/top-summary.md', "#{PRG}.m4")
@coffeeGen.each do |coffee|
@deps.push "gen/#{coffee}.js"
file "gen/#{coffee}.js" => [ "src/#{coffee}.coffee" ] do
sh "coffee -b -o gen/ src/#{coffee}.coffee"
end
end
file 'gen/top-summary.md' => [ 'info.yml' ] do
sh tool_doc_top
end
file "out/#{PRG}.js" => @deps do
sh "m4 -I ../../lib -P #{PRG}.m4 > out/#{PRG}.js"
end
Added less files to the workflow
require 'rake/clean'
CLOBBER.include("out/#{PRG}.js")
CLEAN.include('gen/top-summary.md')
tool_doc_top = "#{File.dirname(__FILE__)}/doc-top"
defaultFiles = [ "out/#{PRG}.js" ]
@coffeeGen ||= []
@deps.push('gen/top-summary.md', "#{PRG}.m4")
@coffeeGen.each do |coffee|
@deps.push "gen/#{coffee}.js"
file "gen/#{coffee}.js" => [ "src/#{coffee}.coffee" ] do
sh "coffee -b -o gen/ src/#{coffee}.coffee"
end
end
@less.each do |from, to|
defaultFiles.push to
file to => [ from ] do
sh "lessc --yui-compress #{from} #{to}"
end
end
file 'gen/top-summary.md' => [ 'info.yml' ] do
sh tool_doc_top
end
file "out/#{PRG}.js" => @deps do
sh "m4 -I ../../lib -P #{PRG}.m4 > out/#{PRG}.js"
end
task :default => defaultFiles
|
Pod::Spec.new do |s|
s.name = "UIImageView-FastImageCache"
s.version = "0.0.1"
s.summary = "A Simple Wrapper With FastImageCache (released by Path Inc)"
s.description = <<-DESC
UIImageView+FastImageCache
* Markdown format.
* Don't worry about the indent, we strip it!
DESC
s.homepage = "https://github.com/pan286/UIImageView-FastImageCache"
s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "pan286" => "pan286@gmail.com" }
s.source = { :git => "https://github.com/pan286/UIImageView-FastImageCache.git", :tag => s.version.to_s }
s.platform = :ios, '6.0'
s.ios.deployment_target = '6.0'
# s.osx.deployment_target = '10.7'
s.requires_arc = true
s.source_files = 'Classes/ios/*.{h,m}'
s.resources = 'Assets'
s.ios.exclude_files = 'Classes/osx'
s.osx.exclude_files = 'Classes/ios'
s.public_header_files = 'Classes/**/UIImageView+FastImageCache.h'
# s.frameworks = 'SomeFramework', 'AnotherFramework'
s.dependency 'FastImageCache', '~> 1.2'
end
Release 0.1.0
Pod::Spec.new do |s|
s.name = "UIImageView-FastImageCache"
s.version = "0.1.0"
s.summary = "A Simple Wrapper With FastImageCache (released by Path Inc)"
s.description = <<-DESC
UIImageView+FastImageCache
* Markdown format.
* Don't worry about the indent, we strip it!
DESC
s.homepage = "https://github.com/pan286/UIImageView-FastImageCache"
s.screenshots = "www.example.com/screenshots_1", "www.example.com/screenshots_2"
s.license = 'MIT'
s.author = { "pan286" => "pan286@gmail.com" }
s.source = { :git => "https://github.com/pan286/UIImageView-FastImageCache.git", :tag => s.version.to_s }
s.platform = :ios, '6.0'
s.ios.deployment_target = '6.0'
# s.osx.deployment_target = '10.7'
s.requires_arc = true
s.source_files = 'Classes/ios/*.{h,m}'
s.resources = 'Assets'
s.ios.exclude_files = 'Classes/osx'
s.osx.exclude_files = 'Classes/ios'
s.public_header_files = 'Classes/**/UIImageView+FastImageCache.h'
# s.frameworks = 'SomeFramework', 'AnotherFramework'
s.dependency 'FastImageCache', '~> 1.2'
end
|
# coding: utf-8
Gem::Specification.new do |spec|
spec.name = "transit-ruby"
spec.version = "0.8.dev"
spec.authors = ["Russ Olsen","David Chelimsky","Yoko Harada"]
spec.email = ["russ@cognitect.com","dchelimsky@cognitect.com","yoko@cognitect.com"]
spec.summary = %q{Transit marshalling for Ruby}
spec.description = %q{Transit marshalling for Ruby}
spec.homepage = "http://github.com/cognitect/transit-ruby"
spec.license = "Apache License 2.0"
spec.required_ruby_version = '>= 1.9.3'
spec.files = `git ls-files -- lib/*`.split("\n") + ["README.md","LICENSE",".yardopts",".yard_redcarpet_ext"]
spec.test_files = `git ls-files -- spec/*`.split("\n")
spec.require_paths = ["lib"]
spec.add_dependency "addressable", "~> 2.3.6", ">= 2.3.6"
spec.add_dependency "msgpack", "~> 0.5.8", ">= 0.5.8"
spec.add_dependency "oj", "~> 2.9.9", ">= 2.9.9"
spec.add_development_dependency "yard", "~> 0.8.7.4", ">= 0.8.7.4"
spec.add_development_dependency "redcarpet", "~> 3.1.1", ">= 3.1.1"
spec.add_development_dependency "yard-redcarpet-ext", "~> 0.0.3", ">= 0.0.3"
spec.add_development_dependency "rake", "~> 10.1"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "wrong", "~> 0.7.1", ">= 0.7.1"
private_key = File.expand_path('~/.gem/transit-ruby-private_key.pem')
if File.exist?(private_key) && ENV['SIGN'] == 'true'
spec.signing_key = private_key
spec.cert_chain = [File.expand_path('~/.gem/transit-ruby-public_cert.pem')]
end
end
bump oj to 2.10.0
# coding: utf-8
Gem::Specification.new do |spec|
spec.name = "transit-ruby"
spec.version = "0.8.dev"
spec.authors = ["Russ Olsen","David Chelimsky","Yoko Harada"]
spec.email = ["russ@cognitect.com","dchelimsky@cognitect.com","yoko@cognitect.com"]
spec.summary = %q{Transit marshalling for Ruby}
spec.description = %q{Transit marshalling for Ruby}
spec.homepage = "http://github.com/cognitect/transit-ruby"
spec.license = "Apache License 2.0"
spec.required_ruby_version = '>= 1.9.3'
spec.files = `git ls-files -- lib/*`.split("\n") + ["README.md","LICENSE",".yardopts",".yard_redcarpet_ext"]
spec.test_files = `git ls-files -- spec/*`.split("\n")
spec.require_paths = ["lib"]
spec.add_dependency "addressable", "~> 2.3.6", ">= 2.3.6"
spec.add_dependency "msgpack", "~> 0.5.8", ">= 0.5.8"
spec.add_dependency "oj", "~> 2.10.0", ">= 2.10.0"
spec.add_development_dependency "yard", "~> 0.8.7.4", ">= 0.8.7.4"
spec.add_development_dependency "redcarpet", "~> 3.1.1", ">= 3.1.1"
spec.add_development_dependency "yard-redcarpet-ext", "~> 0.0.3", ">= 0.0.3"
spec.add_development_dependency "rake", "~> 10.1"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "wrong", "~> 0.7.1", ">= 0.7.1"
private_key = File.expand_path('~/.gem/transit-ruby-private_key.pem')
if File.exist?(private_key) && ENV['SIGN'] == 'true'
spec.signing_key = private_key
spec.cert_chain = [File.expand_path('~/.gem/transit-ruby-public_cert.pem')]
end
end
|
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'activerecord-session_store'
s.version = '0.1.1'
s.summary = 'An Action Dispatch session store backed by an Active Record class.'
s.required_ruby_version = '>= 1.9.3'
s.license = 'MIT'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'https://github.com/rails/activerecord-session_store'
s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.md', 'lib/**/*']
s.require_path = 'lib'
s.extra_rdoc_files = %w( README.md )
s.rdoc_options.concat ['--main', 'README.md']
s.add_dependency('activerecord', '>= 4.0.0', '< 5')
s.add_dependency('actionpack', '>= 4.0.0', '< 5')
s.add_dependency('railties', '>= 4.0.0', '< 5')
s.add_development_dependency('sqlite3')
s.add_development_dependency('appraisal')
end
Bump to 0.1.2
Fixes problem with logger silencer being removed in newer version of
Rails.
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'activerecord-session_store'
s.version = '0.1.2'
s.summary = 'An Action Dispatch session store backed by an Active Record class.'
s.required_ruby_version = '>= 1.9.3'
s.license = 'MIT'
s.author = 'David Heinemeier Hansson'
s.email = 'david@loudthinking.com'
s.homepage = 'https://github.com/rails/activerecord-session_store'
s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.md', 'lib/**/*']
s.require_path = 'lib'
s.extra_rdoc_files = %w( README.md )
s.rdoc_options.concat ['--main', 'README.md']
s.add_dependency('activerecord', '>= 4.0.0', '< 5')
s.add_dependency('actionpack', '>= 4.0.0', '< 5')
s.add_dependency('railties', '>= 4.0.0', '< 5')
s.add_development_dependency('sqlite3')
s.add_development_dependency('appraisal')
end
|
Pod::Spec.new do | s |
s.name = 'ActionSheetPicker-3.0'
s.version = '1.1.9'
s.summary = 'Better version of ActionSheetPicker with support iOS7 and other improvements.'
s.homepage = 'http://skywinder.github.io/ActionSheetPicker-3.0'
s.license = 'BSD'
s.authors = {
'Petr Korolev' => 'https://github.com/skywinder',
'Tim Cinel' => 'email@timcinel.com',
}
s.source = { :git => 'https://github.com/skywinder/ActionSheetPicker-3.0.git', :tag => "#{s.version}" }
s.screenshots = [ "http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/date.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/distance.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/ipad.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/string.png"]
s.requires_arc = true
s.ios.deployment_target = '6.1'
s.platform = :ios
s.public_header_files = 'ActionSheetPicker.h', 'Pickers/*.{h,m}'
s.source_files = 'ActionSheetPicker.h', 'Pickers/*.{h,m}'
s.framework = 'UIKit'
end
update podscpec
Pod::Spec.new do | s |
s.name = 'ActionSheetPicker-3.0'
s.version = '1.1.8'
s.summary = 'Better version of ActionSheetPicker with support iOS7 and other improvements.'
s.homepage = 'http://skywinder.github.io/ActionSheetPicker-3.0'
s.license = 'BSD'
s.authors = {
'Petr Korolev' => 'https://github.com/skywinder',
'Tim Cinel' => 'email@timcinel.com',
}
s.source = { :git => 'https://github.com/skywinder/ActionSheetPicker-3.0.git', :tag => "#{s.version}" }
s.screenshots = [ "http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/date.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/distance.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/ipad.png",
"http://skywinder.github.io/ActionSheetPicker-3.0/Screenshots/string.png"]
s.requires_arc = true
s.ios.deployment_target = '6.1'
s.platform = :ios
s.public_header_files = 'ActionSheetPicker.h', 'Pickers/*.{h,m}'
s.source_files = 'ActionSheetPicker.h', 'Pickers/*.{h,m}'
s.framework = 'UIKit'
end
|
=begin
Arachni
Copyright (c) 2010-2011 Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>
This is free software; you can copy and distribute and modify
this program under the term of the GPL v2.0 License
(See LICENSE file for details)
=end
module Arachni
module Modules
#
# XSS audit module.<br/>
# It audits links, forms and cookies.
#
#
# @author: Tasos "Zapotek" Laskos
# <tasos.laskos@gmail.com>
# <zapotek@segfault.gr>
# @version: 0.2
#
# @see http://cwe.mitre.org/data/definitions/79.html
# @see http://ha.ckers.org/xss.html
# @see http://secunia.com/advisories/9716/
#
class XSS < Arachni::Module::Base
include Arachni::Module::Utilities
def initialize( page )
super( page )
@results = []
end
def prepare( )
@_injection_strs = [
'<arachni_xss_' + seed,
'<arachni_xss_\'";_' + seed,
]
@_opts = {
:format => [ Format::APPEND | Format::NULL ],
}
end
def run( )
@_injection_strs.each {
|str|
opts = {
:match => str,
:substring => str
}.merge( @_opts )
audit( str, opts )
}
end
def self.info
{
:name => 'XSS',
:description => %q{Cross-Site Scripting module},
:elements => [
Issue::Element::FORM,
Issue::Element::LINK,
Issue::Element::COOKIE,
Issue::Element::HEADER
],
:author => 'Tasos "Zapotek" Laskos <tasos.laskos@gmail.com> ',
:version => '0.2',
:references => {
'ha.ckers' => 'http://ha.ckers.org/xss.html',
'Secunia' => 'http://secunia.com/advisories/9716/'
},
:targets => { 'Generic' => 'all' },
:issue => {
:name => %q{Cross-Site Scripting (XSS)},
:description => %q{Client-side code, like JavaScript, can
be injected into the web application.},
:cwe => '79',
:severity => Issue::Severity::HIGH,
:cvssv2 => '9.0',
:remedy_guidance => '',
:remedy_code => '',
}
}
end
end
end
end
enabled parameter flipping for the xss module
=begin
Arachni
Copyright (c) 2010-2011 Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>
This is free software; you can copy and distribute and modify
this program under the term of the GPL v2.0 License
(See LICENSE file for details)
=end
module Arachni
module Modules
#
# XSS audit module.<br/>
# It audits links, forms and cookies.
#
#
# @author: Tasos "Zapotek" Laskos
# <tasos.laskos@gmail.com>
# <zapotek@segfault.gr>
# @version: 0.2
#
# @see http://cwe.mitre.org/data/definitions/79.html
# @see http://ha.ckers.org/xss.html
# @see http://secunia.com/advisories/9716/
#
class XSS < Arachni::Module::Base
include Arachni::Module::Utilities
def initialize( page )
super( page )
@results = []
end
def prepare( )
@_injection_strs = [
'<arachni_xss_' + seed,
'<arachni_xss_\'";_' + seed,
]
@_opts = {
:format => [ Format::APPEND | Format::NULL ],
:flip_param => true
}
end
def run( )
@_injection_strs.each {
|str|
opts = {
:match => str,
:substring => str
}.merge( @_opts )
audit( str, opts )
}
end
def self.info
{
:name => 'XSS',
:description => %q{Cross-Site Scripting module},
:elements => [
Issue::Element::FORM,
Issue::Element::LINK,
Issue::Element::COOKIE,
Issue::Element::HEADER
],
:author => 'Tasos "Zapotek" Laskos <tasos.laskos@gmail.com> ',
:version => '0.2',
:references => {
'ha.ckers' => 'http://ha.ckers.org/xss.html',
'Secunia' => 'http://secunia.com/advisories/9716/'
},
:targets => { 'Generic' => 'all' },
:issue => {
:name => %q{Cross-Site Scripting (XSS)},
:description => %q{Client-side code, like JavaScript, can
be injected into the web application.},
:cwe => '79',
:severity => Issue::Severity::HIGH,
:cvssv2 => '9.0',
:remedy_guidance => '',
:remedy_code => '',
}
}
end
end
end
end
|
#!/usr/bin/env ruby
# This script looks through an iTunes library and finds duplicate tracks.
# Tracks are considered duplicates if they share an
# (artist, album, disc number, track number) tuple.
#
# This definition of dupe is useful for cases where you may have two versions
# of an album mapped to the same folder (i.e., a US and Europe version) with
# different track names. (And also when you have actual duplicates.)
require "pathname"
# OS X only
MUSIC_DIR = File.expand_path "~/Music/iTunes/iTunes Media/Music"
abort "Cannot find iTunes directory. This script only runs on OS X" if not Pathname.new(MUSIC_DIR).exist?
TRACK_COUNTS = Hash.new { |h, k| h[k] = Hash.new(0) }
NO_DISC = "1"
num_dupe_albums = 0
(Dir.glob(File.join(MUSIC_DIR, "*")) - %w[. ..]).each do |artist_path|
artist = Pathname.new(artist_path).basename.to_path
(Dir.glob(artist_dir = File.join(artist_path, "*")) - %w[. ..]).each do |album_path|
album = Pathname.new(album_path).basename.to_path
TRACK_COUNTS.clear
(Dir.glob(File.join(album_path, "*")) - %w[. ..]).each do |song_path|
song = Pathname.new(song_path).basename.to_path
# assume tracks are numbered in the standard
# iTunes way: optional_disk_number-track
TRACK_COUNTS[$1 || NO_DISC][$2] += 1 if song =~ /^(\d\d?-)?(\d\d)/
end
TRACK_COUNTS.each do |disc, tracks|
if tracks.values.max.nil?
$stderr.puts "No tracks found for #{artist}/#{album}"
elsif tracks.values.max > 1
$stderr.puts "#{artist}/#{album} (disc #{disc})"
num_dupe_albums += 1
end
end
end
end
puts "#{num_dupe_albums} dupe albums"
improve error handling
#!/usr/bin/env ruby
# This script looks through an iTunes library and finds duplicate tracks.
# Tracks are considered duplicates if they share an
# (artist, album, disc number, track number) tuple.
#
# This definition of dupe is useful for cases where you may have two versions
# of an album mapped to the same folder (i.e., a US and Europe version) with
# different track names. (And also when you have actual duplicates.)
require "pathname"
# OS X only
MUSIC_DIR = File.expand_path "~/Music/iTunes/iTunes Media/Music"
abort "Cannot find iTunes directory. This script only runs on OS X" if not Pathname.new(MUSIC_DIR).exist?
TRACK_COUNTS = Hash.new { |h, k| h[k] = Hash.new(0) }
NO_DISC = "single disc album"
num_dupe_albums = 0
(Dir.glob(File.join(MUSIC_DIR, "*")) - %w[. ..]).each do |artist_path|
artist = Pathname.new(artist_path).basename.to_path
(Dir.glob(artist_dir = File.join(artist_path, "*")) - %w[. ..]).each do |album_path|
album = Pathname.new(album_path).basename.to_path
TRACK_COUNTS.clear
(Dir.glob(File.join(album_path, "*")) - %w[. ..]).each do |song_path|
song = Pathname.new(song_path).basename.to_path
# assume tracks are numbered in the standard
# iTunes way: optional_disk_number-track
TRACK_COUNTS[$1 || NO_DISC][$2] += 1 if song =~ /^(\d\d?-)?(\d\d)/
end
TRACK_COUNTS.each do |disc, tracks|
if tracks.values.max.nil?
if disc.nil? || disc == NO_DISC
$stderr.puts "No tracks found for #{artist}/#{album}"
else
$stderr.puts "No tracks found for #{artist}/#{album} (disc #{disc})"
end
$stderr.puts TRACK_COUNTS.inspect
elsif tracks.values.max > 1
if disc.nil? || disc == NO_DISC
$stderr.puts "#{artist}/#{album}"
else
$stderr.puts "#{artist}/#{album} (disc #{disc})"
end
$stderr.puts TRACK_COUNTS.inspect
num_dupe_albums += 1
end
end
end
end
puts "#{num_dupe_albums} dupe albums"
|
class Base < ActiveRecord::Migration
def self.up
create_table :pages do |t|
t.references :parent
t.string :name # should be i18n, searchable
t.boolean :in_menu, :default => true
t.boolean :in_sitemap, :default => true
t.boolean :searchable, :default => true
t.datetime :display_from
t.datetime :display_until
t.integer :position
t.timestamps
t.datetime :deleted_at
end
create_table :page_translations do |t|
t.references :"#{Humpyard::config.table_name_prefix}page"
t.string :locale
t.string :title
t.string :title_for_url
t.text :description
t.timestamps
end
create_table :elements do |t|
t.references :page
t.references :container
t.references :content_data
t.string :content_data_type
t.datetime :display_from
t.datetime :display_until
t.integer :position
t.timestamps
t.datetime :deleted_at
end
create_table :elements_container_elements do |t|
t.timestamps
end
create_table :elements_text_elements do |t|
t.timestamps
end
create_table :elements_text_element_translations do |t|
t.references :"#{Humpyard::config.table_name_prefix}elements_text_element"
t.string :locale
t.text :text
t.timestamps
end
end
def self.down
drop_table :elements_text_element_translations
drop_table :elements_text_element
drop_table :elements
drop_table :page_translations
drop_table :pages
end
end
Fixed another migration issue
Arg - should run tests when playing with db migrate ;)
class Base < ActiveRecord::Migration
def self.up
create_table :pages do |t|
t.references :parent
t.string :name # should be i18n, searchable
t.boolean :in_menu, :default => true
t.boolean :in_sitemap, :default => true
t.boolean :searchable, :default => true
t.datetime :display_from
t.datetime :display_until
t.integer :position
t.timestamps
t.datetime :deleted_at
end
create_table :page_translations do |t|
t.references :"#{Humpyard::config.table_name_prefix}page"
t.string :locale
t.string :title
t.string :title_for_url
t.text :description
t.timestamps
end
create_table :elements do |t|
t.references :page
t.references :container
t.references :content_data
t.string :content_data_type
t.datetime :display_from
t.datetime :display_until
t.integer :position
t.timestamps
t.datetime :deleted_at
end
create_table :elements_container_elements do |t|
t.timestamps
end
create_table :elements_text_elements do |t|
t.timestamps
end
create_table :elements_text_element_translations do |t|
t.references :"#{Humpyard::config.table_name_prefix}elements_text_element"
t.string :locale
t.text :content
t.timestamps
end
end
def self.down
drop_table :elements_text_element_translations
drop_table :elements_text_element
drop_table :elements
drop_table :page_translations
drop_table :pages
end
end |
# create payments based on the totals since they can't be known in YAML (quantities are random)
method = Spree::PaymentMethod.where(:name => 'Credit Card', :active => true).first
# Hack the current method so we're able to return a gateway without a RAILS_ENV
Spree::Gateway.class_eval do
def self.current
Spree::Gateway::Bogus.new
end
end
# This table was previously called spree_creditcards, and older migrations
# reference it as such. Make it explicit here that this table has been renamed.
Spree::CreditCard.table_name = 'spree_credit_cards'
creditcard = Spree::CreditCard.create(:cc_type => 'visa', :month => 12, :year => 2014, :last_digits => '1111',
:name => 'Sean Schofield', :gateway_customer_profile_id => 'BGS-1234')
Spree::Order.all.each_with_index do |order, index|
order.update!
payment = order.payments.create!(:amount => order.total, :source => creditcard.clone, :payment_method => method)
payment.update_columns(:state => 'pending', :response_code => '12345')
end
change payment variables
# create payments based on the totals since they can't be known in YAML (quantities are random)
method = Spree::PaymentMethod.where(:name => 'Credit Card', :active => true).first
# Hack the current method so we're able to return a gateway without a RAILS_ENV
Spree::Gateway.class_eval do
def self.current
Spree::Gateway::Bogus.new
end
end
# This table was previously called spree_creditcards, and older migrations
# reference it as such. Make it explicit here that this table has been renamed.
Spree::CreditCard.table_name = 'spree_credit_cards'
creditcard = Spree::CreditCard.create(:cc_type => 'visa', :month => 12, :year => 2014, :last_digits => '1111',
:first_name => 'Sean', :last_name => 'Schofield',
:gateway_customer_profile_id => 'BGS-1234')
Spree::Order.all.each_with_index do |order, index|
order.update!
payment = order.payments.create!(:amount => order.total, :source => creditcard.clone, :payment_method => method)
payment.update_columns(:state => 'pending', :response_code => '12345')
end
|
#!/usr/bin/env ruby
require 'csv'
require 'securerandom'
# We need to read in a CSV like we're getting from Tom Helmuth, and then
# generate two new CSV files, one with the nodes and one with the edges
# (i.e., parent-child relationships).
# We may need to do something with indexing, but auto-indexing may take
# care of that for us.
# The plan is that you'll call this like:
# ruby split_for_batch_imports data6.csv
# and it will generate two new files: data6_nodes.csv and data6_edges.csv
# The headers for replace-space-with-newline are:
# uuid,generation,location,parent_uuids,genetic_operators,
# push_program_size,plush_genome_size,push_program,plush_genome,
# total_error,TC0,TC1,TC2,...,TC199
# We need to replace all the dashes in the headers with underscores,
# and it would be good to glob all the errors into an array instead of
# individual columns.
input_file = ARGV[0]
dirname = File.dirname(input_file)
basename = File.basename(input_file, ".csv")
node_file = File.join(dirname, basename + "_nodes.csv")
edge_file = File.join(dirname, basename + "_edges.csv")
run_uuid = SecureRandom.uuid()
dashes_to_newlines = lambda { |str| str.gsub('-', '_') }
def parse_parent_uuids(str)
str = str[1...-1]
parent_uuids = str.split(" ")
end
# name:string:users
printed_headers = false
CSV.open(node_file, "wb") do |nodes|
CSV.open(edge_file, "wb") do |edges|
num_rows = 0
edges << ["uuid:string:individuals", "uuid:string:individuals", "type"]
CSV.open(input_file, "r",
:headers => true,
:header_converters => dashes_to_newlines,
:converters => [:numeric]) do |inputs|
inputs.each do |row|
if not printed_headers
headers = inputs.headers
headers -= ["parent_uuids"]
headers += ["run_uuid"]
headers[headers.index("uuid")] = "uuid:string:individuals"
nodes << headers
printed_headers = true
end
parent_ids = parse_parent_uuids(row["parent_uuids"])
row.delete("parent_uuids")
row["run_uuid"] = run_uuid
row["uuid"] = '"' + row["uuid"] + '"'
row["plush_genome"] = row["plush_genome"].gsub("\\", "\\\\\\")
row["push_program"] = row["push_program"].gsub("\\", "\\\\\\")
nodes << row
# p parent_ids
parent_ids.each do |parent_uuid|
# p parent_uuid.gsub('"', '')
edges << [parent_uuid, row["uuid"], "PARENT_OF"]
end
end
end
end
end
Added syntax for `batch_import` calls.
I added a comment with an example of how to call `batch_import` to the end of the `split_for_batch_imports.rb` file, and cleaned up some clutter that I'd left behind.
#!/usr/bin/env ruby
require 'csv'
require 'securerandom'
# We need to read in a CSV like we're getting from Tom Helmuth, and then
# generate two new CSV files, one with the nodes and one with the edges
# (i.e., parent-child relationships).
# We may need to do something with indexing, but auto-indexing may take
# care of that for us.
# The plan is that you'll call this like:
# ruby split_for_batch_imports data6.csv
# and it will generate two new files: data6_nodes.csv and data6_edges.csv
# The headers for replace-space-with-newline are:
# uuid,generation,location,parent_uuids,genetic_operators,
# push_program_size,plush_genome_size,push_program,plush_genome,
# total_error,TC0,TC1,TC2,...,TC199
# We need to replace all the dashes in the headers with underscores,
# and it would be good to glob all the errors into an array instead of
# individual columns.
input_file = ARGV[0]
dirname = File.dirname(input_file)
basename = File.basename(input_file, ".csv")
node_file = File.join(dirname, basename + "_nodes.csv")
edge_file = File.join(dirname, basename + "_edges.csv")
run_uuid = SecureRandom.uuid()
dashes_to_newlines = lambda { |str| str.gsub('-', '_') }
def parse_parent_uuids(str)
str = str[1...-1]
parent_uuids = str.split(" ")
end
printed_headers = false
CSV.open(node_file, "wb") do |nodes|
CSV.open(edge_file, "wb") do |edges|
num_rows = 0
edges << ["uuid:string:individuals", "uuid:string:individuals", "type"]
CSV.open(input_file, "r",
:headers => true,
:header_converters => dashes_to_newlines,
:converters => [:numeric]) do |inputs|
inputs.each do |row|
if not printed_headers
headers = inputs.headers
headers -= ["parent_uuids"]
headers += ["run_uuid"]
headers[headers.index("uuid")] = "uuid:string:individuals"
nodes << headers
printed_headers = true
end
parent_ids = parse_parent_uuids(row["parent_uuids"])
row.delete("parent_uuids")
row["run_uuid"] = run_uuid
row["uuid"] = '"' + row["uuid"] + '"'
row["plush_genome"] = row["plush_genome"].gsub("\\", "\\\\\\")
row["push_program"] = row["push_program"].gsub("\\", "\\\\\\")
nodes << row
parent_ids.each do |parent_uuid|
edges << [parent_uuid, row["uuid"], "PARENT_OF"]
end
end
end
end
end
# Syntax for calling batch_import:
# ./import.sh test.db ../data/data6_nodes.csv ../data/data6_edges.csv
|
REST-client test for SIJC certificate ready base64 submission.
require './rest'
require 'base64'
user = "***REMOVED***"
pass = "***REMOVED***"
url = "http://localhost:9000/v1/cap/transaction/certificate_ready"
# payload = JSON.parse('{"first_name" : "Andrés", "last_name" : "Colón",
# "mother_last_name" : "Pérez", "ssn" : "111-22-3333",
# "license" : "12345678", "birth_date" : "01/01/1982",
# "residency" : "San Juan", "IP" : "192.168.1.2",
# "reason" : "Solicitud de Empleo", "birth_place" : "San Juan",
# "email" : "acolon@ogp.pr.gov", "license_number" : "1234567"}')
file = File.open("sagan.jpg", "rb")
contents = file.read
cert64 = Base64.encode64(contents)
id = '1e29234ee0c84921adec08fbe5980162'
payload = { "id" => id,
"certificate_base64" => cert64 }
payload = { "id" => id, "certificate_base64" => 'aW4gd2hpY2ggd2UgZmxvYXQsIGxpa2UgYSBtb2F0IG9mIGR1c3QgaW4gdGhl\nIG1vcm5pbmcgc2t5\n'}
method = "put"
type = "json"
a = Rest.new(url, user, pass, type, payload, method)
a.request
|
help to setup the dbs?
require 'rubygems'
require 'fileutils'
require 'yaml'
require 'erb'
require 'socket'
require 'highline/import'
@hosts = ['localhost','127.0.0.1']
@hosts << IPSocket.getaddress(Socket.gethostname)
@hosts << Socket.gethostname
puts "using db localhosts: #{@hosts.join(', ')}"
FULL_PATH = File.expand_path(__FILE__)
RAILS_ROOT = File.dirname(File.dirname(FULL_PATH))
puts "using RAILS_ROOT = #{RAILS_ROOT}"
@db_admin_username = 'root'
@db_admin_username = ask(" mysql admin user: ") { |q| q.default = "admin" }
@db_admin_pass = ask(" mysql admin password: ") { |q| q.default = "password" }
# LATER: We might want to add remote DB hosts?
def rails_file_path(*args)
File.join([RAILS_ROOT] + args)
end
def create_db(hash)
database = hash['database']
username = hash['username']
password = hash['password']
# delete first:
%x[ mysqladmin -f -u #{@db_admin_username} -p#{@db_admin_pass} drop #{database} ]
%x[ mysqladmin -f -u #{@db_admin_username} -p#{@db_admin_pass} create #{database} ]
@hosts.each do |h|
# puts %Q[ mysql mysql -u #{@db_admin_username} -p#{@db_admin_pass} -e "drop user '#{username}'@'#{h}';" ]
# %x[ mysql mysql -u #{@db_admin_username} -p#{@db_admin_pass} -e "drop user '#{username}'@'#{h}';" ]
puts %Q[ mysql mysql -u #{@db_admin_username} -p#{@db_admin_pass} -e "create user '#{username}'@'#{h}' identified by '#{password}';" ]
%x[ mysql mysql -u #{@db_admin_username} -p#{@db_admin_pass} -e "create user '#{username}'@'#{h}' identified by '#{password}';" ]
puts %Q[mysql mysql -u #{@db_admin_username} -p#{@db_admin_pass} -e "grant all privileges on #{database}.* to '#{username}'@'#{h}' with grant option;" ]
%x[ mysql mysql -u #{@db_admin_username} -p#{@db_admin_pass} -e "grant all privileges on #{database}.* to '#{username}'@'#{h}' with grant option;" ]
end
end
db_config_path = rails_file_path(%w{config database.yml})
if File.exists?(db_config_path)
@db_config = YAML::load_file(db_config_path)
@db_config.each do |c|
puts c.class
puts c.inspect
if c[1]
puts c[1].class
create_db c[1]
end
end
else
puts " couldn't find the database config file: #{db_config_path}"
end
|
#!/usr/bin/env ruby
# Check the Nagios JSON interface provided by nagios-api (TODO: Add link and doc)
# This is pattern for querying the Nagios server
require 'chef/search/query'
require 'date'
require 'json'
require 'logger'
require 'mixlib/cli'
require 'net/https'
# == CLI - Set up an options parser
class ChronosCheckCli
include Mixlib::CLI
option :env,
:boolean => false,
:default => '_default',
:description => 'Chef environment queried for Chronos nodes',
:long => '--env ENVIRONMENT',
:short => '-e ENVIRONMENT'
option :config,
:boolean => false,
:default => %w(~/.chef/knife.rb ~/.chef/client.rb /etc/chef/knife.rb /etc/chef/client.rb),
:description => 'Path to Chef configuration file',
:long => '--config PATH',
:required => false,
:short => '-c PATH'
option :nagios_check,
:boolean => false,
:default => 'test-echo',
:description => 'Run a Nagios check against Chronos Task <TASK>',
:long => '--task TASK',
:required => false,
:short => '-t TASK'
option :proto,
:boolean => true,
:default => false,
:description => 'Specify HTTPS to contact the Chronos server (defaults to HTTP)',
:long => '--https',
:required => false
option :state_file,
:boolean => false,
:default => '/tmp/chronos-state.json',
:description => 'Path to the state file',
:long => '--state-file PATH',
:required => false
option :state_file_age,
:boolean => false,
:default => 3,
:description => 'Amount of time to allow before timing out and refreshing the state file',
:long => '--state-timeout MINUTES',
:required => false
option :verbose,
:boolean => true,
:default => false,
:description => 'Turn on verbose logging',
:long => '--verbose',
:required => true,
:short => '-v'
option :help,
:boolean => true,
:default => false,
:description => 'Show this help message',
:exit => 0,
:long => '--help',
:on => :tail,
:short => '-h',
:show_options => true
end
# == ChronosCheck - a class to find a Chronos node and query it for task status.
class ChronosCheck
# === Initialize Class
# For now feed in the port and protocol.
def initialize(*args) # ChronosCheck.new(chef_environment, chef_config, chronos_protocol, state_file, state_file_age)
@chef_environment = "#{args[0]}"||'_default'
args[1] = args[1].split(/, /) if args[1].class == 'String'
@chef_configs = args[1]||%w(~/.chef/knife.rb ~/.chef/client.rb /etc/chef/knife.rb /etc/chef/client.rb)
@chronos_proto = args[2]||'http'
@state_file = File.expand_path(args[3])||'/tmp/chronos-state.json'
@state_file_age = args[4]||3
@logger = Logger.new(STDOUT)
end
# === Configure Chronos Server using Chef
def get_chef_node
# Set up logging
# If our target environment doesn't exist, fail gracefully.
available_environments = Chef::Environment.list.keys
raise @logger.fatal("Environment does not exist on Chef server! #{@chef_environment}") unless
available_environments.include?(@chef_environment)
# Configure Chef for this instance of the class.
@chef_configs.each do |config|
if ! File.exist?(config)
next
elsif ! Chef::Config.from_file(File.expand_path(config))
next
else
raise @logger.fatal("Could not load configuration from: #{@chef_configs.join(', ')}")
end
end
# Search Chef for nodes that are running the Chronos recipe in the selected
# @chef_environment. Pick a server at random from the list.
chef_query = Chef::Search::Query.new
raise @logger.fatal("Could not find a Cronos node in #{@chef_environment}") unless
( chronos_node_name =
chef_query.search('node', "recipes:*chronos* AND chef_environment:#{@chef_environment}")[0]
.sample.name )
# Load the Chronos server's Chef node data
# noinspection RubyResolve
raise @logger.fatal("Could not load node data for #{chronos_node_name}") unless
( chronos_node = Chef::Node.load(chronos_node_name.to_s) )
# Set the Chronos server's base URL.
@chronos_base_url = "#{@chronos_proto}://#{chronos_node['fqdn']}:#{chronos_node['chronos']['http_port']}"
# Return the Node object as the output of the method.
chronos_node
end
# === Get State from the Chronos Server
def refresh_state
self.get_chef_node
begin
chronos_url = URI.parse("#{@chronos_base_url}/scheduler/jobs")
# Get task data from the Chronos API
chronos_response = JSON.parse(Net::HTTP.get(chronos_url)).sort_by { |task| task['name'] }
state_data = {
:chronos_url => chronos_url,
:query_time => DateTime.now,
:tasks => chronos_response
}
@state_data = state_data
# Write to the State file
File.open(@state_file, 'w') do |file|
file.write(JSON.pretty_generate(@state_data))
end
rescue
raise @logger.fatal("Could not generate state data in file #{@state_file} from #{chronos_url}")
end
end
# === Check for state freshness and update if necessary
def state_timer
# Set the time the state file expires, based on @state_file_age
state_file_expires_on = DateTime.now - Rational(@state_file_age.to_i, 1440)
# If the state file doesn't exist, refresh state data and write state file
if ! File.exist?(@state_file)
self.refresh_state
# Else if the state file exists, test its validity
elsif File.exist?(@state_file)
# Get the state file's timestamp.
state_file_timestamp = DateTime.parse(JSON.parse(File.read(@state_file))['query_time'])
# TODO: If the file timestamp and doesn't match the modify time, assume tampering and refresh state data.
# Refresh state unless the state file's timestamp shows that it hasn't yet expired.
self.refresh_state unless state_file_timestamp < state_file_expires_on
else
false
end
end
# === Parse tasks from the state file.
def parse_tasks
# Refresh state if needed, set up variables.
self.state_timer
chronos_tasks = JSON.parse(File.read(@state_file))
chronos_domain = URI.parse(chronos_tasks['chronos_url']).host.split('.').drop(1).join('.')
# Prepare state information for Nagios checks
task_data = []
chronos_tasks['tasks'].each do |task|
# Parse the success and error times if any have been recorded.
#(task['epsilon'] == '') ?
# epsilon = nil :
# epsilon = Date.parse(task['epsilon'])
(task['lastError'] == '') ?
last_error = nil :
last_error = DateTime.parse(task['lastError'])
(task['lastSuccess'] == '') ?
last_success = nil :
last_success = DateTime.parse(task['lastSuccess'])
# Output a Nagios WARNING if the task is disabled.
if task['disabled']
status = 1
output = "#{task['name']} WARNING: Task disabled!"
# Output a Nagios CRITICAL for enabled tasks with no successes or failure
elsif ! last_error && ! last_success
status = 2
output = "#{task['name']} CRITICAL: Task cannot run! No successful or failed runs."
# Output a Nagios CRITICAL for tasks that are failing with no successes
elsif last_error && ! last_success
status = 2
output = "#{task['name']} CRITICAL: Task cannot run! No successes, recorded last failure at #{last_error}"
# Output a Nagios OK for tasks that have succeeded with no failures. TODO: Make sure this is within epsilon
elsif last_success && ! last_error
status = 0
output = "#{task['name']} OK: Task no failures detected, last success recorded at #{last_success}"
# Output a Nagios OK for tasks with current success status
elsif last_success > last_error
status = 0
output = "#{task['name']} OK: Task success recorded at #{last_success}"
# Output a Nagios CRITICAL for tasks with a current failing status. TODO: Make sure this is within epsilon
elsif last_error > last_success
status = 2
output = "#{task['name']} CRITICAL: Task failed! Error recorded at #{last_success}"
# TODO: Output a Nagios CRITICAL for tasks that fail to meet their epsilon
#elsif epsilon > ( last_success + epsilon )
# status = 2
# output = "#{task['name']} CRITICAL: Task did not run within its epsilon! Last run at #{last_success}"
# If none of these tests match, then we are in an unknown state
else
status = 3
output = "#{task['name']} UNKNOWN: No conditions match known task state!"
end
# Return a hash in preparation for sending a REST call to Nagios
task_data << {
:host => "chronos.#{chronos_domain}",
:service => task['name'],
:status => status,
:output => output#,
}
end
task_data
end
# === TODO: Write out the Nagios commands definition and chronos host.
def write_nagios_config
task_list = self.parse_tasks
task_list.each do |task|
puts JSON.pretty_generate(task)
end
end
# === TODO: Post Chronos task data to Nagios via nagios-api
def post_nagios
JSON.pretty_generate(self.parse_tasks)
end
# === Submit a check for an individual Chronos task.
def post_nrpe(task_name)
nrpe_task = self.parse_tasks.select { |task| task[:service] == task_name }.first
puts nrpe_task[:output]
exit(status=nrpe_task[:status].to_i)
end
end
# == Do some work now!
# === Parse the CLI
cli_data = ChronosCheckCli.new
cli_data.parse_options
cli_state_file = File.expand_path(cli_data.config[:state_file])
cli_state_file_age = cli_data.config[:state_file_age].to_i
if cli_data.config[:proto]
cli_proto = 'https'
else
cli_proto = 'http'
end
# === Execute the checks requested by the user.
my_check = ChronosCheck.new(cli_data.config[:env], cli_data.config[:config], cli_proto, cli_state_file, cli_state_file_age)
my_check.post_nrpe(cli_data.config[:nagios_check])
[scripts] More updates!
#!/usr/bin/env ruby
# Check the Nagios JSON interface provided by nagios-api (TODO: Add link and doc)
# This is pattern for querying the Nagios server
require 'chef/search/query'
require 'date'
require 'json'
require 'logger'
require 'mixlib/cli'
require 'net/https'
# == CLI - Set up an options parser
class ChronosCheckCli
include Mixlib::CLI
# Help text
help_text = <<-EOF
Show this help message
chronos_check - a Nagios check for AirBnB Chronos.
Syntax Detail:
A valid Chef Environment and a verb are required at minimum.
chronos_check -e <chev_environment> /-t|-p|-w/ [long_options]
Searches Chef for nodes running the Chronos recipe in their run_lists
Writes Nagios configuration files from a query of Chronos tasks.
Produces a Nagios/NRPE check result for a named task.
Posts to Zorkian's Nagios API (https://github.com/zorkian/nagios-api).
Proprietary License - Do Not Distribute
EOF
description_env = <<-EOF
Chef Environment - chronos_check searches
the specified Chef Environment to find
nodes with the Chronos recipe in their run
lists. Defaults to _default
EOF
description_config = <<-EOF
Path to Chef configuration file(s)
chronos_check attempts to load configuration
file(s) in order until one of them loads
successfully. chronos_check is preconfigured
to search Chef configuration files in the
following order:
${HOME}/.chef/knife.rb
${HOME}/.chef/client.rb
/etc/chef/knife.rb
/etc/chef/client.rb
EOF
description_nagios_check = <<-EOF
Nagios Check - Return a Nagios check
result from named Chronos Task <task>.
chronos_check will output standard Nagios
check messages exit codes.
EOF
description_nagios_api = <<-EOF
Post to Nagios API - Post all checks to
Nagios API. (You must have Zorkian's
Nagios API installed and running. See
https://github.com/zorkian/nagios-api
EOF
description_write_config = <<-EOF
Write to Nagios config files - Process
Chronos task names into individual Nagios
checks. chronos_check is hard-coded to
write to /etc/nagios/commands/chronos_check.cfg
and /etc/nagios/objects/servers/<chronos_host>.cfg
EOF
# === Required Arguments
# A Chef environment and configuration are required; however these defaults
# should allow this command to run even if no arguments are given.
option :env,
:boolean => false,
:default => '_default',
:description => description_env,
:long => '--env <chef_environment>',
:required => false,
:short => '-e ENVIRONMENT'
option :chef_config,
:boolean => false,
:default => %w(~/.chef/knife.rb ~/.chef/client.rb /etc/chef/knife.rb /etc/chef/client.rb),
:description => description_config,
:long => '--config <path>',
:required => false,
:short => '-c PATH'
# === Verbs - Short Options Only
option :nagios_check,
:boolean => false,
:description => description_nagios_check,
:required => false,
:short => '-t <chronos_task_name>'
option :post_api,
:boolean => true,
:default => false,
:description => description_nagios_api,
:required => false,
:short => '-p'
option :write_config,
:boolean => true,
:default => false,
:description => description_write_config,
:required => false,
:short => '-w'
# === Configuration - Long Options Only
option :proto,
:boolean => true,
:default => false,
:description => 'Specify HTTPS to contact the Chronos server (defaults to HTTP)',
:long => '--https',
:required => false
option :state_file,
:boolean => false,
:default => '/tmp/chronos-state.json',
:description => 'Path to the state file',
:long => '--state-file <path>',
:required => false
option :state_file_age,
:boolean => false,
:default => 3,
:description => 'Amount of time to allow before timing out and refreshing the state file',
:long => '--state-timeout <minutes>',
:required => false
option :verbose,
:boolean => true,
:default => false,
:description => 'Turn on verbose logging',
:long => '--verbose',
:required => true,
:short => '-v'
option :help,
:boolean => true,
:default => false,
:description => help_text,
:exit => 0,
:long => '--help',
:on => :tail,
:short => '-h',
:show_options => true
end
# == ChronosCheck - a class to find a Chronos node and query it for task status.
class ChronosCheck
# === Initialize Class
# For now feed in the port and protocol.
def initialize(*args) # ChronosCheck.new(chef_environment, chef_config, chronos_protocol, state_file, state_file_age)
@chef_environment = "#{args[0]}"||'_default'
args[1] = args[1].split(/, /) if args[1].class == 'String'
@chef_configs = args[1]||%w(~/.chef/knife.rb ~/.chef/client.rb /etc/chef/knife.rb /etc/chef/client.rb)
@chronos_proto = args[2]||'http'
@state_file = File.expand_path(args[3])||'/tmp/chronos-state.json'
@state_file_age = args[4]||3
@logger = Logger.new(STDOUT)
end
# === Configure Chronos Server using Chef
def get_chef_node
# Set up logging
# If our target environment doesn't exist, fail gracefully.
available_environments = Chef::Environment.list.keys
raise @logger.fatal("Environment does not exist on Chef server! #{@chef_environment}") unless
available_environments.include?(@chef_environment)
# Configure Chef for this instance of the class.
@chef_configs.each do |config|
if ( ! File.exist?(config) ) && ( config == @chef_configs.last )
raise @logger.fatal("Could not load Chef configuration from: #{@chef_configs.join(', ')}")
elsif ! File.exist?(config)
next
elsif ! Chef::Config.from_file(File.expand_path(config))
next
else
raise @logger.fatal("Could not load Chef configuration from: #{config}")
end
end
# Search Chef for nodes that are running the Chronos recipe in the selected
# @chef_environment. Pick a server at random from the list.
chef_query = Chef::Search::Query.new
raise @logger.fatal("Could not find a Cronos node in #{@chef_environment}") unless
( chronos_node_name =
chef_query.search('node', "recipes:*chronos* AND chef_environment:#{@chef_environment}")[0]
.sample.name )
# Load the Chronos server's Chef node data
# noinspection RubyResolve
raise @logger.fatal("Could not load node data for #{chronos_node_name}") unless
( chronos_node = Chef::Node.load(chronos_node_name.to_s) )
# Set the Chronos server's base URL.
@chronos_base_url = "#{@chronos_proto}://#{chronos_node['fqdn']}:#{chronos_node['chronos']['http_port']}"
# Return the Node object as the output of the method.
chronos_node
end
# === Get State from the Chronos Server
def refresh_state
self.get_chef_node
begin
chronos_url = URI.parse("#{@chronos_base_url}/scheduler/jobs")
# Get task data from the Chronos API
chronos_response = JSON.parse(Net::HTTP.get(chronos_url)).sort_by { |task| task['name'] }
state_data = {
:chronos_url => chronos_url,
:query_time => DateTime.now,
:tasks => chronos_response
}
@state_data = state_data
# Write to the State file
File.open(@state_file, 'w') do |file|
file.write(JSON.pretty_generate(@state_data))
end
rescue
raise @logger.fatal("Could not generate state data in file #{@state_file} from #{chronos_url}")
end
end
# === Check for state freshness and update if necessary
def state_timer
# Set the time the state file expires, based on @state_file_age
state_file_expires_on = DateTime.now - Rational(@state_file_age.to_i, 1440)
# If the state file doesn't exist, refresh state data and write state file
if ! File.exist?(@state_file)
self.refresh_state
# Else if the state file exists, test its validity
elsif File.exist?(@state_file)
# Get the state file's timestamp.
state_file_timestamp = DateTime.parse(JSON.parse(File.read(@state_file))['query_time'])
# TODO: If the file timestamp and doesn't match the modify time, assume tampering and refresh state data.
# Refresh state unless the state file's timestamp shows that it hasn't yet expired.
self.refresh_state unless state_file_timestamp < state_file_expires_on
else
false
end
end
# === Parse tasks from the state file.
def parse_tasks
# Refresh state if needed, set up variables.
self.state_timer
chronos_tasks = JSON.parse(File.read(@state_file))
chronos_domain = URI.parse(chronos_tasks['chronos_url']).host.split('.').drop(1).join('.')
# Prepare state information for Nagios checks
task_data = []
chronos_tasks['tasks'].each do |task|
# Parse the success and error times if any have been recorded.
(task['lastError'] == '') ?
last_error = nil :
last_error = DateTime.parse(task['lastError'])
(task['lastSuccess'] == '') ?
last_success = nil :
last_success = DateTime.parse(task['lastSuccess'])
# Output a Nagios WARNING if the task is disabled.
if task['disabled']
status = 1
output = "#{task['name']} WARNING: Task disabled!"
# Output a Nagios CRITICAL for enabled tasks with no successes or failure
elsif ! last_error && ! last_success
status = 2
output = "#{task['name']} CRITICAL: Task cannot run! No successful or failed runs."
# Output a Nagios CRITICAL for tasks that are failing with no successes
elsif last_error && ! last_success
status = 2
output = "#{task['name']} CRITICAL: Task cannot run! No successes, recorded last failure at #{last_error}"
# Output a Nagios OK for tasks that have succeeded with no failures. TODO: Make sure this is within epsilon
elsif last_success && ! last_error
status = 0
output = "#{task['name']} OK: Task reports success at #{last_success}"
# Output a Nagios OK for tasks with current success status
elsif last_success > last_error
status = 0
output = "#{task['name']} OK: Task reports recovery at #{last_success} from error at #{last_error}"
# Output a Nagios CRITICAL for tasks with a current failing status. TODO: Make sure this is within epsilon
elsif last_error > last_success
status = 2
output = "#{task['name']} CRITICAL: Task failed! Error recorded at #{last_success}"
# TODO: Output a Nagios CRITICAL for tasks that fail to meet their schedule. Here is the formula:
# Parse the schedule
#elsif epsilon > ( last_success + epsilon )
# status = 2
# output = "#{task['name']} CRITICAL: Task did not run within its epsilon! Last run at #{last_success}"
# If none of these tests match, then we are in an unknown state
else
status = 3
output = "#{task['name']} UNKNOWN: No conditions match known task state!"
end
# Return a hash in preparation for sending a REST call to Nagios
task_data << {
:host => "chronos.#{chronos_domain}",
:service => task['name'],
:status => status,
:output => output#,
}
end
task_data
end
# === TODO: Write out the Nagios commands definition and chronos host.
def write_nagios_config
task_list = self.parse_tasks
task_list.each do |task|
puts JSON.pretty_generate(task)
end
end
# === TODO: Post Chronos task data to Nagios via nagios-api
def post_nagios
JSON.pretty_generate(self.parse_tasks)
end
# === Submit a check for an individual Chronos task.
def post_nrpe(task_name)
nrpe_task = self.parse_tasks.select { |task| task[:service] == task_name }.first
puts nrpe_task[:output]
exit(status=nrpe_task[:status].to_i)
end
end
# == Do some work now!
# Use the classes defined above to perform the checks.
# === Parse the CLI
cli_data = ChronosCheckCli.new
cli_data.parse_options
cli_state_file = File.expand_path(cli_data.config[:state_file])
cli_state_file_age = cli_data.config[:state_file_age].to_i
if cli_data.config[:proto]
cli_proto = 'https'
else
cli_proto = 'http'
end
# === Display help if no options are given
if ARGV.empty?
raise cli_data.config[:help]
end
# === Execute the checks requested by the user.
exec_check = ChronosCheck.new(cli_data.config[:env], cli_data.config[:config], cli_proto, cli_state_file, cli_state_file_age)
if cli_data.config[:post_api]
puts exec_check.post_nagios
end
if cli_data.config[:write_config]
puts 'TODO: Write config'
end
if cli_data.config[:nagios_check]
exec_check.post_nrpe(cli_data.config[:nagios_check])
end
|
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "devise_security_extension"
s.version = "0.7.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Marco Scholl", "Alexander Dreher"]
s.date = "2012-11-23"
s.description = "An enterprise security extension for devise, trying to meet industrial standard security demands for web applications."
s.email = "team@phatworx.de"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"app/controllers/devise/password_expired_controller.rb",
"app/views/devise/password_expired/show.html.erb",
"config/locales/de.yml",
"config/locales/en.yml",
"devise_security_extension.gemspec",
"lib/devise_security_extension.rb",
"lib/devise_security_extension/controllers/helpers.rb",
"lib/devise_security_extension/hooks/expirable.rb",
"lib/devise_security_extension/hooks/password_expirable.rb",
"lib/devise_security_extension/hooks/session_limitable.rb",
"lib/devise_security_extension/models/expirable.rb",
"lib/devise_security_extension/models/old_password.rb",
"lib/devise_security_extension/models/password_archivable.rb",
"lib/devise_security_extension/models/password_expirable.rb",
"lib/devise_security_extension/models/secure_validatable.rb",
"lib/devise_security_extension/models/security_question.rb",
"lib/devise_security_extension/models/security_questionable.rb",
"lib/devise_security_extension/models/session_limitable.rb",
"lib/devise_security_extension/orm/active_record.rb",
"lib/devise_security_extension/patches.rb",
"lib/devise_security_extension/patches/confirmations_controller_captcha.rb",
"lib/devise_security_extension/patches/confirmations_controller_security_question.rb",
"lib/devise_security_extension/patches/passwords_controller_captcha.rb",
"lib/devise_security_extension/patches/passwords_controller_security_question.rb",
"lib/devise_security_extension/patches/registrations_controller_captcha.rb",
"lib/devise_security_extension/patches/sessions_controller_captcha.rb",
"lib/devise_security_extension/patches/unlocks_controller_captcha.rb",
"lib/devise_security_extension/patches/unlocks_controller_security_question.rb",
"lib/devise_security_extension/rails.rb",
"lib/devise_security_extension/routes.rb",
"lib/devise_security_extension/schema.rb",
"lib/generators/devise_security_extension/install_generator.rb",
"test/helper.rb",
"test/test_devise_security_extension.rb"
]
s.homepage = "http://github.com/phatworx/devise_security_extension"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "Security extension for devise"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rails>, [">= 3.1.1"])
s.add_runtime_dependency(%q<devise>, [">= 2.0.0"])
s.add_development_dependency(%q<rails_email_validator>, [">= 0"])
s.add_development_dependency(%q<easy_captcha>, [">= 0"])
s.add_development_dependency(%q<bundler>, [">= 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"])
else
s.add_dependency(%q<rails>, [">= 3.1.1"])
s.add_dependency(%q<devise>, [">= 2.0.0"])
s.add_dependency(%q<rails_email_validator>, [">= 0"])
s.add_dependency(%q<easy_captcha>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
else
s.add_dependency(%q<rails>, [">= 3.1.1"])
s.add_dependency(%q<devise>, [">= 2.0.0"])
s.add_dependency(%q<rails_email_validator>, [">= 0"])
s.add_dependency(%q<easy_captcha>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
end
Depend on Railties, not Rails
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = "devise_security_extension"
s.version = "0.7.2"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Marco Scholl", "Alexander Dreher"]
s.date = "2012-11-23"
s.description = "An enterprise security extension for devise, trying to meet industrial standard security demands for web applications."
s.email = "team@phatworx.de"
s.extra_rdoc_files = [
"LICENSE.txt",
"README.rdoc"
]
s.files = [
".document",
"Gemfile",
"Gemfile.lock",
"LICENSE.txt",
"README.rdoc",
"Rakefile",
"VERSION",
"app/controllers/devise/password_expired_controller.rb",
"app/views/devise/password_expired/show.html.erb",
"config/locales/de.yml",
"config/locales/en.yml",
"devise_security_extension.gemspec",
"lib/devise_security_extension.rb",
"lib/devise_security_extension/controllers/helpers.rb",
"lib/devise_security_extension/hooks/expirable.rb",
"lib/devise_security_extension/hooks/password_expirable.rb",
"lib/devise_security_extension/hooks/session_limitable.rb",
"lib/devise_security_extension/models/expirable.rb",
"lib/devise_security_extension/models/old_password.rb",
"lib/devise_security_extension/models/password_archivable.rb",
"lib/devise_security_extension/models/password_expirable.rb",
"lib/devise_security_extension/models/secure_validatable.rb",
"lib/devise_security_extension/models/security_question.rb",
"lib/devise_security_extension/models/security_questionable.rb",
"lib/devise_security_extension/models/session_limitable.rb",
"lib/devise_security_extension/orm/active_record.rb",
"lib/devise_security_extension/patches.rb",
"lib/devise_security_extension/patches/confirmations_controller_captcha.rb",
"lib/devise_security_extension/patches/confirmations_controller_security_question.rb",
"lib/devise_security_extension/patches/passwords_controller_captcha.rb",
"lib/devise_security_extension/patches/passwords_controller_security_question.rb",
"lib/devise_security_extension/patches/registrations_controller_captcha.rb",
"lib/devise_security_extension/patches/sessions_controller_captcha.rb",
"lib/devise_security_extension/patches/unlocks_controller_captcha.rb",
"lib/devise_security_extension/patches/unlocks_controller_security_question.rb",
"lib/devise_security_extension/rails.rb",
"lib/devise_security_extension/routes.rb",
"lib/devise_security_extension/schema.rb",
"lib/generators/devise_security_extension/install_generator.rb",
"test/helper.rb",
"test/test_devise_security_extension.rb"
]
s.homepage = "http://github.com/phatworx/devise_security_extension"
s.licenses = ["MIT"]
s.require_paths = ["lib"]
s.rubygems_version = "1.8.24"
s.summary = "Security extension for devise"
if s.respond_to? :specification_version then
s.specification_version = 3
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<railties>, [">= 3.1.1"])
s.add_runtime_dependency(%q<devise>, [">= 2.0.0"])
s.add_development_dependency(%q<rails_email_validator>, [">= 0"])
s.add_development_dependency(%q<easy_captcha>, [">= 0"])
s.add_development_dependency(%q<bundler>, [">= 1.0.0"])
s.add_development_dependency(%q<jeweler>, ["~> 1.8.4"])
else
s.add_dependency(%q<railties>, [">= 3.1.1"])
s.add_dependency(%q<devise>, [">= 2.0.0"])
s.add_dependency(%q<rails_email_validator>, [">= 0"])
s.add_dependency(%q<easy_captcha>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
else
s.add_dependency(%q<railties>, [">= 3.1.1"])
s.add_dependency(%q<devise>, [">= 2.0.0"])
s.add_dependency(%q<rails_email_validator>, [">= 0"])
s.add_dependency(%q<easy_captcha>, [">= 0"])
s.add_dependency(%q<bundler>, [">= 1.0.0"])
s.add_dependency(%q<jeweler>, ["~> 1.8.4"])
end
end
|
#!/usr/bin/env ruby
require 'bundler/setup'
Bundler.require(:default)
require 'appscript'
require 'yaml'
require 'keychain'
require 'jira'
require 'ruby-growl'
require 'pathname'
class Hash
#take keys of hash and transform those to a symbols
def self.transform_keys_to_symbols(value)
return value if not value.is_a?(Hash)
hash = value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
return hash
end
end
if File.file?(ENV['HOME']+'/.jofsync.yaml')
config = YAML.load_file(ENV['HOME']+'/.jofsync.yaml')
config = Hash.transform_keys_to_symbols(config)
=begin
YAML CONFIG EXAMPLE
---
jira:
hostname: 'http://example.atlassian.net'
context: 'Colleagues'
project: 'Jira'
filter: 'resolution = Unresolved and issue in watchedissues()'
=end
end
opts = Trollop::options do
banner ""
banner <<-EOS
Jira OmniFocus Sync Tool
Usage:
jofsync [options]
KNOWN ISSUES:
* With long names you must use an equal sign ( i.e. --hostname=test-target-1 )
---
EOS
version 'jofsync 1.1.0'
opt :hostname, 'Jira Server Hostname', :type => :string, :short => 'h', :default => config[:jira][:hostname]
opt :context, 'OF Default Context', :type => :string, :short => 'c', :default => config[:jira][:context]
opt :project, 'OF Default Project', :type => :string, :short => 'r', :default => config[:jira][:project]
opt :filter, 'JQL Filter', :type => :string, :short => 'j', :default => config[:jira][:filter]
opt :parenttaskfield, 'Field to use in identifying parent tasks', :default => config[:jira][:parenttaskfield]
opt :quiet, 'Disable alerts', :short => 'q', :default => config[:jira][:quiet]
end
QUIET = opts[:quiet]
unless QUIET
Growler = Growl.new "localhost", Pathname.new($0).basename
Growler.add_notification 'Error'
Growler.add_notification 'No Results'
Growler.add_notification 'Context Created'
Growler.add_notification 'Task Created'
Growler.add_notification 'Task Not Completed'
Growler.add_notification 'Task Completed'
end
#JIRA Configuration
JIRA_BASE_URL = opts[:hostname]
uri = URI(JIRA_BASE_URL)
host = uri.host
path = uri.path
uri.path = ''
keychainitem = Keychain.internet_passwords.where(:server => host).first
USERNAME = keychainitem.account
JIRACLIENT = JIRA::Client.new(
:username => USERNAME,
:password => keychainitem.password,
:site => uri.to_s,
:context_path => path,
:auth_type => :basic
)
QUERY = opts[:filter]
JQL = URI::encode(QUERY)
#OmniFocus Configuration
DEFAULT_CONTEXT = opts[:context]
DEFAULT_PROJECT = opts[:project]
ParentTaskField = opts[:parenttaskfield]
# This method adds a new Task to OmniFocus based on the new_task_properties passed in
def add_task(omnifocus_document, project:nil, parent_task:nil, context:nil, **new_task_properties)
# If there is a passed in OF project name, get the actual project object
if project
proj = omnifocus_document.flattened_tasks[project]
end
# Check to see if there's already an OF Task with that name in the referenced Project
name = new_task_properties[:name]
flagged = new_task_properties[:flagged]
task = proj.flattened_tasks.get.find { |t| t.name.get.force_encoding("UTF-8") == name }
if task
# Make sure the flag is set correctly.
task.flagged.set(flagged)
if task.completed.get == true
task.completed.set(false)
QUIET or Growler.notify 'Task Not Completed', task.name.get, "OmniFocus task no longer marked completed"
end
task.completed.set(false)
return task
else
defaultctx = omnifocus_document.flattened_contexts[DEFAULT_CONTEXT]
# If there is a passed in OF context name, get the actual context object (creating if necessary)
if context
unless ctx = defaultctx.contexts.get.find { |c| c.name.get.force_encoding("UTF-8") == context }
ctx = defaultctx.make(:new => :context, :with_properties => {:name => context})
QUIET or Growler.notify 'Context Created', "#{defaultctx.name.get}: #{context}", 'OmniFocus context created'
end
else
ctx = defaultctx
end
# If there is a passed in parent task, get the actual parent task object (creating if necessary)
if parent_task
unless parent = proj.tasks.get.find { |t| t.name.get.force_encoding("UTF-8") == parent_task }
parent = proj.make(:new => :task,
:with_properties => {:name => parent_task,
:sequential => false,
:completed_by_children => true})
QUIET or Growler.notify 'Task Created', parent_task, 'OmniFocus task created'
end
end
# Update the context property to be the actual context object not the context name
new_task_properties[:context] = ctx
# You can uncomment this line and comment the one below if you want the tasks to end up in your Inbox instead of a specific Project
# new_task = omnifocus_document.make(:new => :inbox_task, :with_properties => new_task_properties)
# Make a new Task in the Project
task = proj.make(:new => :task,
:at => parent,
:with_properties => new_task_properties)
QUIET or Growler.notify 'Task Created', name, 'OmniFocus task created'
return task
end
end
# This method is responsible for getting your assigned Jira Tickets and adding them to OmniFocus as Tasks
def add_jira_tickets_to_omnifocus ()
# Get the open Jira issues assigned to you
fields = ['summary', 'reporter', 'assignee', 'duedate']
if ParentTaskField
fields.push ParentTaskField
end
results = JIRACLIENT.Issue.jql(QUERY, fields: fields)
if results.nil?
QUIET or Growler.notify 'No Results', Pathname.new($0).basename, "No results from Jira"
exit
end
# Get the OmniFocus app and main document via AppleScript
omnifocus_app = Appscript.app.by_name("OmniFocus")
omnifocus_document = omnifocus_app.default_document
# Iterate through resulting issues.
results.each do |ticket|
jira_id = ticket.key
add_task(omnifocus_document,
# Create the task name by adding the ticket summary to the jira ticket key
name: "#{jira_id}: #{ticket.summary}",
project: DEFAULT_PROJECT,
# Base context on the reporter
#context: ticket.reporter.attrs["displayName"]
context: ticket.reporter.attrs["displayName"].split(", ").reverse.join(" "),
# Create the task notes with the Jira Ticket URL
note: "#{JIRA_BASE_URL}/browse/#{jira_id}",
# Flag the task iff it's assigned to me.
flagged: ((not ticket.assignee.nil?) and ticket.assignee.attrs["name"] == USERNAME),
# Get parent task, if any
parent_task: ticket.fields[ParentTaskField],
# Get due date, if any
due_date: (ticket.duedate && Date.parse(ticket.duedate))
)
end
end
def mark_resolved_jira_tickets_as_complete_in_omnifocus ()
# get tasks from the project
omnifocus_app = Appscript.app.by_name("OmniFocus")
omnifocus_document = omnifocus_app.default_document
ctx = omnifocus_document.flattened_contexts[DEFAULT_CONTEXT]
ctx.flattened_contexts.get.each do |ctx|
tasks = ctx.tasks.get
tasks.each do |task|
if !task.completed.get && task.note.get.match(JIRA_BASE_URL)
# try to parse out jira id
full_url= task.note.get
jira_id=full_url.sub(JIRA_BASE_URL+"/browse/","")
ticket = JIRACLIENT.Issue.find(jira_id)
status = ticket.fields["status"]
if ['Closed', 'Resolved'].include? status["name"]
# if resolved, mark it as complete in OmniFocus
if task.completed.get == false
task.completed.set(true)
QUIET or Growler.notify 'Task Completed', task.name.get, "OmniFocus task marked completed"
end
end
end
end
end
end
def app_is_running(app_name)
`ps aux` =~ /#{app_name}/ ? true : false
end
def main ()
if app_is_running("OmniFocus")
add_jira_tickets_to_omnifocus
mark_resolved_jira_tickets_as_complete_in_omnifocus
end
end
main
Tighten up code
#!/usr/bin/env ruby
require 'bundler/setup'
Bundler.require(:default)
require 'appscript'
require 'yaml'
require 'keychain'
require 'jira'
require 'ruby-growl'
require 'pathname'
class Hash
#take keys of hash and transform those to a symbols
def self.transform_keys_to_symbols(value)
return value if not value.is_a?(Hash)
hash = value.inject({}){|memo,(k,v)| memo[k.to_sym] = Hash.transform_keys_to_symbols(v); memo}
return hash
end
end
if File.file?(ENV['HOME']+'/.jofsync.yaml')
config = YAML.load_file(ENV['HOME']+'/.jofsync.yaml')
config = Hash.transform_keys_to_symbols(config)
=begin
YAML CONFIG EXAMPLE
---
jira:
hostname: 'http://example.atlassian.net'
context: 'Colleagues'
project: 'Jira'
filter: 'resolution = Unresolved and issue in watchedissues()'
=end
end
opts = Trollop::options do
banner ""
banner <<-EOS
Jira OmniFocus Sync Tool
Usage:
jofsync [options]
KNOWN ISSUES:
* With long names you must use an equal sign ( i.e. --hostname=test-target-1 )
---
EOS
version 'jofsync 1.1.0'
opt :hostname, 'Jira Server Hostname', :type => :string, :short => 'h', :default => config[:jira][:hostname]
opt :context, 'OF Default Context', :type => :string, :short => 'c', :default => config[:jira][:context]
opt :project, 'OF Default Project', :type => :string, :short => 'r', :default => config[:jira][:project]
opt :filter, 'JQL Filter', :type => :string, :short => 'j', :default => config[:jira][:filter]
opt :parenttaskfield, 'Field to use in identifying parent tasks', :default => config[:jira][:parenttaskfield]
opt :quiet, 'Disable alerts', :short => 'q', :default => config[:jira][:quiet]
end
QUIET = opts[:quiet]
unless QUIET
Growler = Growl.new "localhost", Pathname.new($0).basename
Growler.add_notification 'Error'
Growler.add_notification 'No Results'
Growler.add_notification 'Context Created'
Growler.add_notification 'Task Created'
Growler.add_notification 'Task Not Completed'
Growler.add_notification 'Task Completed'
end
#JIRA Configuration
JIRA_BASE_URL = opts[:hostname]
uri = URI(JIRA_BASE_URL)
host = uri.host
path = uri.path
uri.path = ''
keychainitem = Keychain.internet_passwords.where(:server => host).first
USERNAME = keychainitem.account
JIRACLIENT = JIRA::Client.new(
:username => USERNAME,
:password => keychainitem.password,
:site => uri.to_s,
:context_path => path,
:auth_type => :basic
)
QUERY = opts[:filter]
JQL = URI::encode(QUERY)
#OmniFocus Configuration
DEFAULT_CONTEXT = opts[:context]
DEFAULT_PROJECT = opts[:project]
ParentTaskField = opts[:parenttaskfield]
# This method adds a new Task to OmniFocus based on the new_task_properties passed in
def add_task(omnifocus_document, project:nil, parent_task:nil, context:nil, **new_task_properties)
# If there is a passed in OF project name, get the actual project object
if project
proj = omnifocus_document.flattened_tasks[project]
end
# Check to see if there's already an OF Task with that name in the referenced Project
if task = proj.flattened_tasks.get.find { |t| t.name.get.force_encoding("UTF-8") == new_task_properties[:name] }
# Make sure the flag is set correctly.
task.flagged.set(new_task_properties[:flagged])
if task.completed.get == true
task.completed.set(false)
QUIET or Growler.notify 'Task Not Completed', task.name.get, "OmniFocus task no longer marked completed"
end
task.completed.set(false)
return task
else
defaultctx = omnifocus_document.flattened_contexts[DEFAULT_CONTEXT]
# If there is a passed in OF context name, get the actual context object (creating if necessary)
if context
unless ctx = defaultctx.contexts.get.find { |c| c.name.get.force_encoding("UTF-8") == context }
ctx = defaultctx.make(:new => :context, :with_properties => {:name => context})
QUIET or Growler.notify 'Context Created', "#{defaultctx.name.get}: #{context}", 'OmniFocus context created'
end
else
ctx = defaultctx
end
# If there is a passed in parent task, get the actual parent task object (creating if necessary)
if parent_task
unless parent = proj.tasks.get.find { |t| t.name.get.force_encoding("UTF-8") == parent_task }
parent = proj.make(:new => :task,
:with_properties => {:name => parent_task,
:sequential => false,
:completed_by_children => true})
QUIET or Growler.notify 'Task Created', parent_task, 'OmniFocus task created'
end
end
# Update the context property to be the actual context object not the context name
new_task_properties[:context] = ctx
# You can uncomment this line and comment the one below if you want the tasks to end up in your Inbox instead of a specific Project
# new_task = omnifocus_document.make(:new => :inbox_task, :with_properties => new_task_properties)
# Make a new Task in the Project
task = proj.make(:new => :task,
:at => parent,
:with_properties => new_task_properties)
QUIET or Growler.notify 'Task Created', name, 'OmniFocus task created'
return task
end
end
# This method is responsible for getting your assigned Jira Tickets and adding them to OmniFocus as Tasks
def add_jira_tickets_to_omnifocus ()
# Get the open Jira issues assigned to you
fields = ['summary', 'reporter', 'assignee', 'duedate']
if ParentTaskField
fields.push ParentTaskField
end
results = JIRACLIENT.Issue.jql(QUERY, fields: fields)
if results.nil?
QUIET or Growler.notify 'No Results', Pathname.new($0).basename, "No results from Jira"
exit
end
# Get the OmniFocus app and main document via AppleScript
omnifocus_app = Appscript.app.by_name("OmniFocus")
omnifocus_document = omnifocus_app.default_document
# Iterate through resulting issues.
results.each do |ticket|
jira_id = ticket.key
add_task(omnifocus_document,
# Create the task name by adding the ticket summary to the jira ticket key
name: "#{jira_id}: #{ticket.summary}",
project: DEFAULT_PROJECT,
# Base context on the reporter
#context: ticket.reporter.attrs["displayName"]
context: ticket.reporter.attrs["displayName"].split(", ").reverse.join(" "),
# Create the task notes with the Jira Ticket URL
note: "#{JIRA_BASE_URL}/browse/#{jira_id}",
# Flag the task iff it's assigned to me.
flagged: ((not ticket.assignee.nil?) and ticket.assignee.attrs["name"] == USERNAME),
# Get parent task, if any
parent_task: ticket.fields[ParentTaskField],
# Get due date, if any
due_date: (ticket.duedate && Date.parse(ticket.duedate))
)
end
end
def mark_resolved_jira_tickets_as_complete_in_omnifocus ()
# get tasks from the project
omnifocus_app = Appscript.app.by_name("OmniFocus")
omnifocus_document = omnifocus_app.default_document
ctx = omnifocus_document.flattened_contexts[DEFAULT_CONTEXT]
ctx.flattened_contexts.get.each do |ctx|
tasks = ctx.tasks.get
tasks.each do |task|
if !task.completed.get && task.note.get.match(JIRA_BASE_URL)
# try to parse out jira id
full_url= task.note.get
jira_id=full_url.sub(JIRA_BASE_URL+"/browse/","")
ticket = JIRACLIENT.Issue.find(jira_id)
status = ticket.fields["status"]
if ['Closed', 'Resolved'].include? status["name"]
# if resolved, mark it as complete in OmniFocus
if task.completed.get == false
task.completed.set(true)
QUIET or Growler.notify 'Task Completed', task.name.get, "OmniFocus task marked completed"
end
end
end
end
end
end
def app_is_running(app_name)
`ps aux` =~ /#{app_name}/ ? true : false
end
def main ()
if app_is_running("OmniFocus")
add_jira_tickets_to_omnifocus
mark_resolved_jira_tickets_as_complete_in_omnifocus
end
end
main
|
add scheduler job
source = 'http://some.remote.host/polarchart.xml'
labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']
SCHEDULER.every '10s', :first_in => 0 do |job|
# Create a random set of data for the chart
data = Array.new(5) { rand(30) }
send_event('polarchart', {
segments: [
{
value: data[0],
color: '#F7464A',
highlight: '#FF5A5E',
label: 'January',
}, {
value: data[1],
color: '#46BFBD',
highlight: '#5AD3D1',
label: 'February',
}, {
value: data[2],
color: '#FDB45C',
highlight: '#FFC870',
label: 'March',
}, {
value: data[3],
color: '#949FB1',
highlight: '#A8B3C5',
label: 'April',
}, {
value: data[4],
color: '#4D5360',
highlight: '#4D5360',
label: 'April',
}
]
})
end
|
require 'oauth/request_proxy/rack_request'
module Lti
extend ActiveSupport::Concern
include LtiHelper
MAXIMUM_SCORE = 1
MAXIMUM_SESSION_AGE = 60.minutes
SESSION_PARAMETERS = %w(launch_presentation_return_url lis_outcome_service_url lis_result_sourcedid)
def build_tool_provider(options = {})
if options[:consumer] && options[:parameters]
IMS::LTI::ToolProvider.new(options[:consumer].oauth_key, options[:consumer].oauth_secret, options[:parameters])
end
end
private :build_tool_provider
# exercise_id.nil? ==> the user has logged out. All session data is to be destroyed
# exercise_id.exists? ==> the user has submitted the results of an exercise to the consumer.
# Only the lti_parameters are deleted.
def clear_lti_session_data(exercise_id = nil)
if (exercise_id.nil?)
LtiParameter.destroy_all(consumers_id: session[:consumer_id], external_user_id: @current_user.external_id)
session.delete(:consumer_id)
session.delete(:external_user_id)
else
LtiParameter.destroy_all(consumers_id: session[:consumer_id],
external_user_id: @current_user.external_id,
exercises_id: exercise_id)
end
end
private :clear_lti_session_data
def consumer_return_url(provider, options = {})
consumer_return_url = provider.try(:launch_presentation_return_url) || params[:launch_presentation_return_url]
consumer_return_url += "?#{options.to_query}" if consumer_return_url && options.present?
consumer_return_url
end
def external_user_email(provider)
provider.lis_person_contact_email_primary
end
private :external_user_email
def external_user_name(provider)
if provider.lis_person_name_full
provider.lis_person_name_full
elsif provider.lis_person_name_given && provider.lis_person_name_family
"#{provider.lis_person_name_given} #{provider.lis_person_name_family}"
else
provider.lis_person_name_given || provider.lis_person_name_family
end
end
private :external_user_name
def refuse_lti_launch(options = {})
return_to_consumer(lti_errorlog: options[:message], lti_errormsg: t('sessions.oauth.failure'))
end
private :refuse_lti_launch
def require_oauth_parameters
refuse_lti_launch(message: t('sessions.oauth.missing_parameters')) unless params[:oauth_consumer_key] && params[:oauth_signature]
end
private :require_oauth_parameters
def require_unique_oauth_nonce
refuse_lti_launch(message: t('sessions.oauth.used_nonce')) if NonceStore.has?(params[:oauth_nonce])
end
private :require_unique_oauth_nonce
def require_valid_consumer_key
@consumer = Consumer.find_by(oauth_key: params[:oauth_consumer_key])
refuse_lti_launch(message: t('sessions.oauth.invalid_consumer')) unless @consumer
end
private :require_valid_consumer_key
def require_valid_exercise_token
@exercise = Exercise.find_by(token: params[:custom_token])
refuse_lti_launch(message: t('sessions.oauth.invalid_exercise_token')) unless @exercise
end
private :require_valid_exercise_token
def require_valid_oauth_signature
@provider = build_tool_provider(consumer: @consumer, parameters: params)
refuse_lti_launch(message: t('sessions.oauth.invalid_signature')) unless @provider.valid_request?(request)
end
private :require_valid_oauth_signature
def return_to_consumer(options = {})
consumer_return_url = @provider.try(:launch_presentation_return_url) || params[:launch_presentation_return_url]
if consumer_return_url
consumer_return_url += "?#{options.to_query}" if options.present?
redirect_to(consumer_return_url)
else
flash[:danger] = options[:lti_errormsg]
flash[:info] = options[:lti_msg]
redirect_to(:root)
end
end
private :return_to_consumer
def send_score(exercise_id, score)
::NewRelic::Agent.add_custom_parameters({ score: score, session: session })
fail(Error, "Score #{score} must be between 0 and #{MAXIMUM_SCORE}!") unless (0..MAXIMUM_SCORE).include?(score)
lti_parameter = LtiParameter.where(consumers_id: session[:consumer_id],
external_user_id: @current_user.external_id,
exercises_id: exercise_id).first
consumer = Consumer.find_by(id: session[:consumer_id])
provider = build_tool_provider(consumer: consumer, parameters: lti_parameter.lti_parameters)
if provider.nil?
{status: 'error'}
elsif provider.outcome_service?
response = provider.post_replace_result!(score)
{code: response.response_code, message: response.post_response.body, status: response.code_major}
else
{status: 'unsupported'}
end
end
private :send_score
def set_current_user
@current_user = ExternalUser.find_or_create_by(consumer_id: @consumer.id, external_id: @provider.user_id)
@current_user.update(email: external_user_email(@provider), name: external_user_name(@provider))
end
private :set_current_user
def store_lti_session_data(options = {})
exercise = Exercise.where(token: options[:parameters][:custom_token]).first
exercise_id = exercise.id unless exercise.nil?
lti_parameters = LtiParameter.find_or_create_by(consumers_id: options[:consumer].id,
external_user_id: options[:parameters][:user_id].to_s,
exercises_id: exercise_id)
lti_parameters.lti_parameters = options[:parameters].slice(*SESSION_PARAMETERS).to_json
lti_parameters.save!
session[:consumer_id] = options[:consumer].id
session[:external_user_id] = @current_user.id
end
private :store_lti_session_data
def store_nonce(nonce)
NonceStore.add(nonce)
end
private :store_nonce
class Error < RuntimeError
end
end
only destroy LTI_parameter when exercise is submitted
require 'oauth/request_proxy/rack_request'
module Lti
extend ActiveSupport::Concern
include LtiHelper
MAXIMUM_SCORE = 1
MAXIMUM_SESSION_AGE = 60.minutes
SESSION_PARAMETERS = %w(launch_presentation_return_url lis_outcome_service_url lis_result_sourcedid)
def build_tool_provider(options = {})
if options[:consumer] && options[:parameters]
IMS::LTI::ToolProvider.new(options[:consumer].oauth_key, options[:consumer].oauth_secret, options[:parameters])
end
end
private :build_tool_provider
# exercise_id.nil? ==> the user has logged out. All session data is to be destroyed
# exercise_id.exists? ==> the user has submitted the results of an exercise to the consumer.
# Only the lti_parameters are deleted.
def clear_lti_session_data(exercise_id = nil)
@current_user = ExternalUser.find(@submission.user_id)
if (exercise_id.nil?)
session.delete(:consumer_id)
session.delete(:external_user_id)
else
LtiParameter.destroy_all(consumers_id: @consumer.id,
external_user_id: @current_user.external_id,
exercises_id: exercise_id)
end
end
private :clear_lti_session_data
def consumer_return_url(provider, options = {})
consumer_return_url = provider.try(:launch_presentation_return_url) || params[:launch_presentation_return_url]
consumer_return_url += "?#{options.to_query}" if consumer_return_url && options.present?
consumer_return_url
end
def external_user_email(provider)
provider.lis_person_contact_email_primary
end
private :external_user_email
def external_user_name(provider)
if provider.lis_person_name_full
provider.lis_person_name_full
elsif provider.lis_person_name_given && provider.lis_person_name_family
"#{provider.lis_person_name_given} #{provider.lis_person_name_family}"
else
provider.lis_person_name_given || provider.lis_person_name_family
end
end
private :external_user_name
def refuse_lti_launch(options = {})
return_to_consumer(lti_errorlog: options[:message], lti_errormsg: t('sessions.oauth.failure'))
end
private :refuse_lti_launch
def require_oauth_parameters
refuse_lti_launch(message: t('sessions.oauth.missing_parameters')) unless params[:oauth_consumer_key] && params[:oauth_signature]
end
private :require_oauth_parameters
def require_unique_oauth_nonce
refuse_lti_launch(message: t('sessions.oauth.used_nonce')) if NonceStore.has?(params[:oauth_nonce])
end
private :require_unique_oauth_nonce
def require_valid_consumer_key
@consumer = Consumer.find_by(oauth_key: params[:oauth_consumer_key])
refuse_lti_launch(message: t('sessions.oauth.invalid_consumer')) unless @consumer
end
private :require_valid_consumer_key
def require_valid_exercise_token
@exercise = Exercise.find_by(token: params[:custom_token])
refuse_lti_launch(message: t('sessions.oauth.invalid_exercise_token')) unless @exercise
end
private :require_valid_exercise_token
def require_valid_oauth_signature
@provider = build_tool_provider(consumer: @consumer, parameters: params)
refuse_lti_launch(message: t('sessions.oauth.invalid_signature')) unless @provider.valid_request?(request)
end
private :require_valid_oauth_signature
def return_to_consumer(options = {})
consumer_return_url = @provider.try(:launch_presentation_return_url) || params[:launch_presentation_return_url]
if consumer_return_url
consumer_return_url += "?#{options.to_query}" if options.present?
redirect_to(consumer_return_url)
else
flash[:danger] = options[:lti_errormsg]
flash[:info] = options[:lti_msg]
redirect_to(:root)
end
end
private :return_to_consumer
def send_score(exercise_id, score)
::NewRelic::Agent.add_custom_parameters({ score: score, session: session })
fail(Error, "Score #{score} must be between 0 and #{MAXIMUM_SCORE}!") unless (0..MAXIMUM_SCORE).include?(score)
lti_parameter = LtiParameter.where(consumers_id: session[:consumer_id],
external_user_id: @current_user.external_id,
exercises_id: exercise_id).first
consumer = Consumer.find_by(id: session[:consumer_id])
provider = build_tool_provider(consumer: consumer, parameters: lti_parameter.lti_parameters)
if provider.nil?
{status: 'error'}
elsif provider.outcome_service?
response = provider.post_replace_result!(score)
{code: response.response_code, message: response.post_response.body, status: response.code_major}
else
{status: 'unsupported'}
end
end
private :send_score
def set_current_user
@current_user = ExternalUser.find_or_create_by(consumer_id: @consumer.id, external_id: @provider.user_id)
#TODO is this really necessary, and does it work at all?
@current_user.update(email: external_user_email(@provider), name: external_user_name(@provider))
end
private :set_current_user
def store_lti_session_data(options = {})
exercise = Exercise.where(token: options[:parameters][:custom_token]).first
exercise_id = exercise.id unless exercise.nil?
lti_parameters = LtiParameter.find_or_create_by(consumers_id: options[:consumer].id,
external_user_id: options[:parameters][:user_id].to_s,
exercises_id: exercise_id)
lti_parameters.lti_parameters = options[:parameters].slice(*SESSION_PARAMETERS).to_json
lti_parameters.save!
session[:consumer_id] = options[:consumer].id
session[:external_user_id] = @current_user.id
end
private :store_lti_session_data
def store_nonce(nonce)
NonceStore.add(nonce)
end
private :store_nonce
class Error < RuntimeError
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mastermind/version'
Gem::Specification.new do |spec|
spec.name = "mastermind"
spec.version = Mastermind::VERSION
spec.authors = ["Oreoluwa Akinniranye"]
spec.email = ["oreoluwa.akinniranye@andela.com"]
spec.summary = %q{Play against the computer by guessing the colors it has stored. You will be amongst the top ten if you got it in fewer guesses and least time}
spec.description = %q{The mastermind game is a game of analysis and guesses. The idea is to guess the colors and the sequence that the computer has generated.}
spec.homepage = "https://github.com/andela-oakinniranye/mastermind"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
# delete this section to allow pushing this gem to any host.
if spec.respond_to?(:metadata)
spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
else
raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
end
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = ['mastermind']
spec.require_paths = ["lib"]
spec.add_dependency "activesupport", "~> 4.2"
spec.add_dependency "colorize"
spec.add_dependency "humanize"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rspec-nc"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "pry"
spec.add_development_dependency "pry-remote"
spec.add_development_dependency "pry-nav"
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
end
removed line in gemspec which was causing the gem to fail
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mastermind/version'
Gem::Specification.new do |spec|
spec.name = "mastermind"
spec.version = Mastermind::VERSION
spec.authors = ["Oreoluwa Akinniranye"]
spec.email = ["oreoluwa.akinniranye@andela.com"]
spec.summary = %q{Play against the computer by guessing the colors it has stored. You will be amongst the top ten if you got it in fewer guesses and least time}
spec.description = %q{The mastermind game is a game of analysis and guesses. The idea is to guess the colors and the sequence that the computer has generated.}
spec.homepage = "https://github.com/andela-oakinniranye/mastermind"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = ['mastermind']
spec.require_paths = ["lib"]
spec.add_dependency "activesupport", "~> 4.2"
spec.add_dependency "colorize"
spec.add_dependency "humanize"
spec.add_development_dependency "rspec"
spec.add_development_dependency "rspec-nc"
spec.add_development_dependency "guard"
spec.add_development_dependency "guard-rspec"
spec.add_development_dependency "pry"
spec.add_development_dependency "pry-remote"
spec.add_development_dependency "pry-nav"
spec.add_development_dependency "bundler", "~> 1.10"
spec.add_development_dependency "rake", "~> 10.0"
end
|
require 'formula'
class HerokuToolbelt < Formula
homepage 'https://toolbelt.heroku.com/other'
url 'http://assets.heroku.com.s3.amazonaws.com/heroku-client/heroku-client-3.3.0.tgz'
sha1 '5c4760414623b3e92bb0deaf5d49da695f8c7ad4'
def install
libexec.install Dir["*"]
bin.write_exec_script libexec/"bin/heroku"
end
test do
system "#{bin}/heroku", "version"
end
# Possibly temporary; see https://github.com/heroku/heroku/issues/1020
def caveats; <<-EOS.undent
heroku-toolbelt requires an installation of Ruby 1.9 or greater.
EOS
end
end
heroku-toolbelt: remove out-of-date comment
require 'formula'
class HerokuToolbelt < Formula
homepage 'https://toolbelt.heroku.com/other'
url 'http://assets.heroku.com.s3.amazonaws.com/heroku-client/heroku-client-3.3.0.tgz'
sha1 '5c4760414623b3e92bb0deaf5d49da695f8c7ad4'
def install
libexec.install Dir["*"]
bin.write_exec_script libexec/"bin/heroku"
end
test do
system "#{bin}/heroku", "version"
end
def caveats; <<-EOS.undent
heroku-toolbelt requires an installation of Ruby 1.9 or greater.
EOS
end
end
|
class LibjsonRpcCpp < Formula
desc "C++ framework for json-rpc"
homepage "https://github.com/cinemast/libjson-rpc-cpp"
url "https://github.com/cinemast/libjson-rpc-cpp/archive/v0.6.0.tar.gz"
sha256 "98baf15e51514339be54c01296f0a51820d2d4f17f8c9d586f1747be1df3290b"
bottle do
cellar :any
revision 2
sha256 "a9d7883a0a265f75495fe23c7414eab1201c49869e76f742437820f64bf7af77" => :el_capitan
sha256 "5d951749422146185149e7e0d57a6ab11dd92d6b55f3bce21b7bd90617e33039" => :yosemite
sha256 "07afaeb45d0cb55fe1cc1770498700046f238c2e01ba39544eb697b72965cd32" => :mavericks
end
depends_on "cmake" => :build
depends_on "argtable"
depends_on "jsoncpp"
depends_on "libmicrohttpd"
def install
system "cmake", ".", *std_cmake_args
system "make"
system "make", "install"
end
test do
system "#{bin}/jsonrpcstub", "-h"
end
end
libjson-rpc-cpp: update 0.6.0 bottle.
class LibjsonRpcCpp < Formula
desc "C++ framework for json-rpc"
homepage "https://github.com/cinemast/libjson-rpc-cpp"
url "https://github.com/cinemast/libjson-rpc-cpp/archive/v0.6.0.tar.gz"
sha256 "98baf15e51514339be54c01296f0a51820d2d4f17f8c9d586f1747be1df3290b"
bottle do
cellar :any
sha256 "b80a2f4618128083bbb25df7eb6b541eca7ae740ddbd931cd5e2067cc4366d6b" => :el_capitan
sha256 "fd3c31a721cdb7bae7390e063f90a7979a3e0021ac1df1a2ed16957f2971ff00" => :yosemite
sha256 "6daf0f22b4917f78226424660e28da52a6aec83183b604ebe94e35bc2a593e95" => :mavericks
end
depends_on "cmake" => :build
depends_on "argtable"
depends_on "jsoncpp"
depends_on "libmicrohttpd"
def install
system "cmake", ".", *std_cmake_args
system "make"
system "make", "install"
end
test do
system "#{bin}/jsonrpcstub", "-h"
end
end
|
require "formula"
require "language/haskell"
class PandocCiteproc < Formula
include Language::Haskell::Cabal
homepage "https://github.com/jgm/pandoc-citeproc"
url "https://hackage.haskell.org/package/pandoc-citeproc-0.4.0.1/pandoc-citeproc-0.4.0.1.tar.gz"
sha1 "41c71939d78bfe52f4dd06ca3d7a6b4d824cdd47"
bottle do
sha1 "e1a339c04e78a4d7fba542336e655f24fa029bbe" => :mavericks
sha1 "b00f823667e3a2775388758af7ed309ddc5a761e" => :mountain_lion
sha1 "332eb0a1d2754606f74731e30ee3e76320947389" => :lion
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "gmp"
depends_on "pandoc" => :recommended
fails_with(:clang) { build 425 } # clang segfaults on Lion
def install
cabal_sandbox do
cabal_install "--only-dependencies"
cabal_install "--prefix=#{prefix}"
end
cabal_clean_lib
end
test do
bib = testpath/"test.bib"
bib.write <<-EOS.undent
@Book{item1,
author="John Doe",
title="First Book",
year="2005",
address="Cambridge",
publisher="Cambridge University Press"
}
EOS
assert `pandoc-citeproc --bib2yaml #{bib}`.include? "- publisher-place: Cambridge"
end
end
pandoc-citeproc 0.6
Closes #32544.
Signed-off-by: Jack Nagel <43386ce32af96f5c56f2a88e458cb94cebee3751@gmail.com>
require "formula"
require "language/haskell"
class PandocCiteproc < Formula
include Language::Haskell::Cabal
homepage "https://github.com/jgm/pandoc-citeproc"
url "https://hackage.haskell.org/package/pandoc-citeproc-0.6/pandoc-citeproc-0.6.tar.gz"
sha1 "5236b4b4e201f94ab9f1bcd0d7e81c4271b46e8f"
bottle do
sha1 "e1a339c04e78a4d7fba542336e655f24fa029bbe" => :mavericks
sha1 "b00f823667e3a2775388758af7ed309ddc5a761e" => :mountain_lion
sha1 "332eb0a1d2754606f74731e30ee3e76320947389" => :lion
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "gmp"
depends_on "pandoc" => :recommended
fails_with(:clang) { build 425 } # clang segfaults on Lion
def install
cabal_sandbox do
cabal_install "--only-dependencies"
cabal_install "--prefix=#{prefix}"
end
cabal_clean_lib
end
test do
bib = testpath/"test.bib"
bib.write <<-EOS.undent
@Book{item1,
author="John Doe",
title="First Book",
year="2005",
address="Cambridge",
publisher="Cambridge University Press"
}
EOS
assert `pandoc-citeproc --bib2yaml #{bib}`.include? "- publisher-place: Cambridge"
end
end
|
require "language/haskell"
class PandocCiteproc < Formula
include Language::Haskell::Cabal
desc "Library and executable for using citeproc with pandoc"
homepage "https://github.com/jgm/pandoc-citeproc"
url "https://hackage.haskell.org/package/pandoc-citeproc-0.7.2/pandoc-citeproc-0.7.2.tar.gz"
sha256 "3eddf364561a8f175493cdd32eb4c7994164d2c27625c07cf13bfd491539f936"
bottle do
sha256 "f11bd1023f207b5c2655e51a7494dbf8e5c065ebaebce2bca6a79fd9c5650360" => :yosemite
sha256 "5262e34bd21b6d3e6eb7bb4883949e17d4268fdb99892d5420a98b237b55c172" => :mavericks
sha256 "b5ebf2ba3ff01756661c748bccdaf8719d7dd7eb03d325bbf17522ff74ee5121" => :mountain_lion
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "pandoc"
setup_ghc_compilers
def install
cabal_sandbox do
cabal_install "--only-dependencies"
cabal_install "--prefix=#{prefix}"
end
cabal_clean_lib
end
test do
bib = testpath/"test.bib"
bib.write <<-EOS.undent
@Book{item1,
author="John Doe",
title="First Book",
year="2005",
address="Cambridge",
publisher="Cambridge University Press"
}
EOS
system "pandoc-citeproc", "--bib2yaml", bib
end
end
pandoc-citeproc 0.7.3
Closes #42812.
Signed-off-by: Dominyk Tiller <53e438f55903875d07efdd98a8aaf887e7208dd3@gmail.com>
require "language/haskell"
class PandocCiteproc < Formula
include Language::Haskell::Cabal
desc "Library and executable for using citeproc with pandoc"
homepage "https://github.com/jgm/pandoc-citeproc"
url "https://hackage.haskell.org/package/pandoc-citeproc-0.7.3/pandoc-citeproc-0.7.3.tar.gz"
sha256 "72fc81d962812d037bb78c6d38d602ca2c6895f0436c8be94cb71600ed288e68"
bottle do
sha256 "f11bd1023f207b5c2655e51a7494dbf8e5c065ebaebce2bca6a79fd9c5650360" => :yosemite
sha256 "5262e34bd21b6d3e6eb7bb4883949e17d4268fdb99892d5420a98b237b55c172" => :mavericks
sha256 "b5ebf2ba3ff01756661c748bccdaf8719d7dd7eb03d325bbf17522ff74ee5121" => :mountain_lion
end
depends_on "ghc" => :build
depends_on "cabal-install" => :build
depends_on "pandoc"
setup_ghc_compilers
def install
cabal_sandbox do
cabal_install "--only-dependencies"
cabal_install "--prefix=#{prefix}"
end
cabal_clean_lib
end
test do
bib = testpath/"test.bib"
bib.write <<-EOS.undent
@Book{item1,
author="John Doe",
title="First Book",
year="2005",
address="Cambridge",
publisher="Cambridge University Press"
}
EOS
system "pandoc-citeproc", "--bib2yaml", bib
end
end
|
require "formula"
class PyenvWhichExt < Formula
homepage "https://github.com/yyuu/pyenv-which-ext"
url "https://github.com/yyuu/pyenv-which-ext/archive/v0.0.2.tar.gz"
sha1 "72d2d3a80d6d9226276dfb897d12f7be69a12f0a"
head "https://github.com/yyuu/pyenv-which-ext.git"
depends_on "pyenv"
def install
ENV["PREFIX"] = prefix
system "./install.sh"
end
end
pyenv-which-ext: add test
Closes #35499.
Signed-off-by: Mike McQuaid <a17fed27eaa842282862ff7c1b9c8395a26ac320@mikemcquaid.com>
class PyenvWhichExt < Formula
homepage "https://github.com/yyuu/pyenv-which-ext"
url "https://github.com/yyuu/pyenv-which-ext/archive/v0.0.2.tar.gz"
sha1 "72d2d3a80d6d9226276dfb897d12f7be69a12f0a"
head "https://github.com/yyuu/pyenv-which-ext.git"
depends_on "pyenv"
def install
ENV["PREFIX"] = prefix
system "./install.sh"
end
test do
shell_output("eval \"$(pyenv init -)\" && pyenv which python")
end
end
|
module IssuablesHelper
include GitlabRoutingHelper
def sidebar_gutter_toggle_icon
sidebar_gutter_collapsed? ? icon('angle-double-left', { 'aria-hidden': 'true' }) : icon('angle-double-right', { 'aria-hidden': 'true' })
end
def sidebar_gutter_collapsed_class
"right-sidebar-#{sidebar_gutter_collapsed? ? 'collapsed' : 'expanded'}"
end
def multi_label_name(current_labels, default_label)
if current_labels && current_labels.any?
title = current_labels.first.try(:title)
if current_labels.size > 1
"#{title} +#{current_labels.size - 1} more"
else
title
end
else
default_label
end
end
def issuable_json_path(issuable)
project = issuable.project
if issuable.is_a?(MergeRequest)
namespace_project_merge_request_path(project.namespace, project, issuable.iid, :json)
else
namespace_project_issue_path(project.namespace, project, issuable.iid, :json)
end
end
def serialize_issuable(issuable)
case issuable
when Issue
IssueSerializer.new.represent(issuable).to_json
when MergeRequest
MergeRequestSerializer
.new(current_user: current_user, project: issuable.project)
.represent(issuable)
.to_json
end
end
def template_dropdown_tag(issuable, &block)
title = selected_template(issuable) || "Choose a template"
options = {
toggle_class: 'js-issuable-selector',
title: title,
filter: true,
placeholder: 'Filter',
footer_content: true,
data: {
data: issuable_templates(issuable),
field_name: 'issuable_template',
selected: selected_template(issuable),
project_path: ref_project.path,
namespace_path: ref_project.namespace.full_path
}
}
dropdown_tag(title, options: options) do
capture(&block)
end
end
def users_dropdown_label(selected_users)
case selected_users.length
when 0
"Unassigned"
when 1
selected_users[0].name
else
"#{selected_users[0].name} + #{selected_users.length - 1} more"
end
end
def user_dropdown_label(user_id, default_label)
return default_label if user_id.nil?
return "Unassigned" if user_id == "0"
user = User.find_by(id: user_id)
if user
user.name
else
default_label
end
end
def project_dropdown_label(project_id, default_label)
return default_label if project_id.nil?
return "Any project" if project_id == "0"
project = Project.find_by(id: project_id)
if project
project.name_with_namespace
else
default_label
end
end
def milestone_dropdown_label(milestone_title, default_label = "Milestone")
title =
case milestone_title
when Milestone::Upcoming.name then Milestone::Upcoming.title
when Milestone::Started.name then Milestone::Started.title
else milestone_title.presence
end
h(title || default_label)
end
def to_url_reference(issuable)
case issuable
when Issue
link_to issuable.to_reference, issue_url(issuable)
when MergeRequest
link_to issuable.to_reference, merge_request_url(issuable)
else
issuable.to_reference
end
end
def issuable_meta(issuable, project, text)
output = content_tag(:strong, class: "identifier") do
concat("#{text} ")
concat(to_url_reference(issuable))
end
output << " opened #{time_ago_with_tooltip(issuable.created_at)} by ".html_safe
output << content_tag(:strong) do
author_output = link_to_member(project, issuable.author, size: 24, mobile_classes: "hidden-xs", tooltip: true)
author_output << link_to_member(project, issuable.author, size: 24, by_username: true, avatar: false, mobile_classes: "hidden-sm hidden-md hidden-lg")
end
output << " ".html_safe
output << content_tag(:span, (issuable.task_status if issuable.tasks?), id: "task_status", class: "hidden-xs hidden-sm")
output << content_tag(:span, (issuable.task_status_short if issuable.tasks?), id: "task_status_short", class: "hidden-md hidden-lg")
output
end
def issuable_todo(issuable)
if current_user
current_user.todos.find_by(target: issuable, state: :pending)
end
end
def issuable_labels_tooltip(labels, limit: 5)
first, last = labels.partition.with_index{ |_, i| i < limit }
label_names = first.collect(&:name)
label_names << "and #{last.size} more" unless last.empty?
label_names.join(', ')
end
def issuables_state_counter_text(issuable_type, state)
titles = {
opened: "Open"
}
state_title = titles[state] || state.to_s.humanize
count = issuables_count_for_state(issuable_type, state)
html = content_tag(:span, state_title)
html << " " << content_tag(:span, number_with_delimiter(count), class: 'badge')
html.html_safe
end
def assigned_issuables_count(issuable_type)
current_user.public_send("assigned_open_#{issuable_type}_count")
end
def issuable_filter_params
[
:search,
:author_id,
:assignee_id,
:milestone_title,
:label_name
]
end
def issuable_reference(issuable)
@show_full_reference ? issuable.to_reference(full: true) : issuable.to_reference(@group || @project)
end
def issuable_filter_present?
issuable_filter_params.any? { |k| params.key?(k) }
end
def issuable_initial_data(issuable)
data = {
endpoint: namespace_project_issue_path(@project.namespace, @project, issuable),
canUpdate: can?(current_user, :update_issue, issuable),
canDestroy: can?(current_user, :destroy_issue, issuable),
canMove: current_user ? issuable.can_move?(current_user) : false,
issuableRef: issuable.to_reference,
isConfidential: issuable.confidential,
markdownPreviewUrl: preview_markdown_path(@project),
markdownDocs: help_page_path('user/markdown'),
projectsAutocompleteUrl: autocomplete_projects_path(project_id: @project.id),
issuableTemplates: issuable_templates(issuable),
projectPath: ref_project.path,
projectNamespace: ref_project.namespace.full_path,
initialTitleHtml: markdown_field(issuable, :title),
initialTitleText: issuable.title,
initialDescriptionHtml: markdown_field(issuable, :description),
initialDescriptionText: issuable.description,
initialTaskStatus: issuable.task_status
}
data.merge!(updated_at_by(issuable))
data.to_json
end
def updated_at_by(issuable)
return {} unless issuable.is_edited?
{
updatedAt: issuable.updated_at.to_time.iso8601,
updatedBy: {
name: issuable.last_edited_by.name,
path: user_path(issuable.last_edited_by)
}
}
end
private
def sidebar_gutter_collapsed?
cookies[:collapsed_gutter] == 'true'
end
def base_issuable_scope(issuable)
issuable.project.send(issuable.class.table_name).send(issuable_state_scope(issuable))
end
def issuable_state_scope(issuable)
if issuable.respond_to?(:merged?) && issuable.merged?
:merged
else
issuable.open? ? :opened : :closed
end
end
def issuables_count_for_state(issuable_type, state, finder: nil)
finder ||= public_send("#{issuable_type}_finder")
cache_key = finder.state_counter_cache_key(state)
@counts ||= {}
@counts[cache_key] ||= Rails.cache.fetch(cache_key, expires_in: 2.minutes) do
finder.count_by_state
end
@counts[cache_key][state]
end
def issuable_templates(issuable)
@issuable_templates ||=
case issuable
when Issue
issue_template_names
when MergeRequest
merge_request_template_names
else
raise 'Unknown issuable type!'
end
end
def merge_request_template_names
@merge_request_templates ||= Gitlab::Template::MergeRequestTemplate.dropdown_names(ref_project)
end
def issue_template_names
@issue_templates ||= Gitlab::Template::IssueTemplate.dropdown_names(ref_project)
end
def selected_template(issuable)
params[:issuable_template] if issuable_templates(issuable).any?{ |template| template[:name] == params[:issuable_template] }
end
def issuable_todo_button_data(issuable, todo, is_collapsed)
{
todo_text: "Add todo",
mark_text: "Mark done",
todo_icon: (is_collapsed ? icon('plus-square') : nil),
mark_icon: (is_collapsed ? icon('check-square', class: 'todo-undone') : nil),
issuable_id: issuable.id,
issuable_type: issuable.class.name.underscore,
url: namespace_project_todos_path(@project.namespace, @project),
delete_path: (dashboard_todo_path(todo) if todo),
placement: (is_collapsed ? 'left' : nil),
container: (is_collapsed ? 'body' : nil)
}
end
end
Make issuables_count_for_state public
This doesn't need to be public in CE, but EE uses it as such.
module IssuablesHelper
include GitlabRoutingHelper
def sidebar_gutter_toggle_icon
sidebar_gutter_collapsed? ? icon('angle-double-left', { 'aria-hidden': 'true' }) : icon('angle-double-right', { 'aria-hidden': 'true' })
end
def sidebar_gutter_collapsed_class
"right-sidebar-#{sidebar_gutter_collapsed? ? 'collapsed' : 'expanded'}"
end
def multi_label_name(current_labels, default_label)
if current_labels && current_labels.any?
title = current_labels.first.try(:title)
if current_labels.size > 1
"#{title} +#{current_labels.size - 1} more"
else
title
end
else
default_label
end
end
def issuable_json_path(issuable)
project = issuable.project
if issuable.is_a?(MergeRequest)
namespace_project_merge_request_path(project.namespace, project, issuable.iid, :json)
else
namespace_project_issue_path(project.namespace, project, issuable.iid, :json)
end
end
def serialize_issuable(issuable)
case issuable
when Issue
IssueSerializer.new.represent(issuable).to_json
when MergeRequest
MergeRequestSerializer
.new(current_user: current_user, project: issuable.project)
.represent(issuable)
.to_json
end
end
def template_dropdown_tag(issuable, &block)
title = selected_template(issuable) || "Choose a template"
options = {
toggle_class: 'js-issuable-selector',
title: title,
filter: true,
placeholder: 'Filter',
footer_content: true,
data: {
data: issuable_templates(issuable),
field_name: 'issuable_template',
selected: selected_template(issuable),
project_path: ref_project.path,
namespace_path: ref_project.namespace.full_path
}
}
dropdown_tag(title, options: options) do
capture(&block)
end
end
def users_dropdown_label(selected_users)
case selected_users.length
when 0
"Unassigned"
when 1
selected_users[0].name
else
"#{selected_users[0].name} + #{selected_users.length - 1} more"
end
end
def user_dropdown_label(user_id, default_label)
return default_label if user_id.nil?
return "Unassigned" if user_id == "0"
user = User.find_by(id: user_id)
if user
user.name
else
default_label
end
end
def project_dropdown_label(project_id, default_label)
return default_label if project_id.nil?
return "Any project" if project_id == "0"
project = Project.find_by(id: project_id)
if project
project.name_with_namespace
else
default_label
end
end
def milestone_dropdown_label(milestone_title, default_label = "Milestone")
title =
case milestone_title
when Milestone::Upcoming.name then Milestone::Upcoming.title
when Milestone::Started.name then Milestone::Started.title
else milestone_title.presence
end
h(title || default_label)
end
def to_url_reference(issuable)
case issuable
when Issue
link_to issuable.to_reference, issue_url(issuable)
when MergeRequest
link_to issuable.to_reference, merge_request_url(issuable)
else
issuable.to_reference
end
end
def issuable_meta(issuable, project, text)
output = content_tag(:strong, class: "identifier") do
concat("#{text} ")
concat(to_url_reference(issuable))
end
output << " opened #{time_ago_with_tooltip(issuable.created_at)} by ".html_safe
output << content_tag(:strong) do
author_output = link_to_member(project, issuable.author, size: 24, mobile_classes: "hidden-xs", tooltip: true)
author_output << link_to_member(project, issuable.author, size: 24, by_username: true, avatar: false, mobile_classes: "hidden-sm hidden-md hidden-lg")
end
output << " ".html_safe
output << content_tag(:span, (issuable.task_status if issuable.tasks?), id: "task_status", class: "hidden-xs hidden-sm")
output << content_tag(:span, (issuable.task_status_short if issuable.tasks?), id: "task_status_short", class: "hidden-md hidden-lg")
output
end
def issuable_todo(issuable)
if current_user
current_user.todos.find_by(target: issuable, state: :pending)
end
end
def issuable_labels_tooltip(labels, limit: 5)
first, last = labels.partition.with_index{ |_, i| i < limit }
label_names = first.collect(&:name)
label_names << "and #{last.size} more" unless last.empty?
label_names.join(', ')
end
def issuables_state_counter_text(issuable_type, state)
titles = {
opened: "Open"
}
state_title = titles[state] || state.to_s.humanize
count = issuables_count_for_state(issuable_type, state)
html = content_tag(:span, state_title)
html << " " << content_tag(:span, number_with_delimiter(count), class: 'badge')
html.html_safe
end
def assigned_issuables_count(issuable_type)
current_user.public_send("assigned_open_#{issuable_type}_count")
end
def issuable_filter_params
[
:search,
:author_id,
:assignee_id,
:milestone_title,
:label_name
]
end
def issuable_reference(issuable)
@show_full_reference ? issuable.to_reference(full: true) : issuable.to_reference(@group || @project)
end
def issuable_filter_present?
issuable_filter_params.any? { |k| params.key?(k) }
end
def issuable_initial_data(issuable)
data = {
endpoint: namespace_project_issue_path(@project.namespace, @project, issuable),
canUpdate: can?(current_user, :update_issue, issuable),
canDestroy: can?(current_user, :destroy_issue, issuable),
canMove: current_user ? issuable.can_move?(current_user) : false,
issuableRef: issuable.to_reference,
isConfidential: issuable.confidential,
markdownPreviewUrl: preview_markdown_path(@project),
markdownDocs: help_page_path('user/markdown'),
projectsAutocompleteUrl: autocomplete_projects_path(project_id: @project.id),
issuableTemplates: issuable_templates(issuable),
projectPath: ref_project.path,
projectNamespace: ref_project.namespace.full_path,
initialTitleHtml: markdown_field(issuable, :title),
initialTitleText: issuable.title,
initialDescriptionHtml: markdown_field(issuable, :description),
initialDescriptionText: issuable.description,
initialTaskStatus: issuable.task_status
}
data.merge!(updated_at_by(issuable))
data.to_json
end
def updated_at_by(issuable)
return {} unless issuable.is_edited?
{
updatedAt: issuable.updated_at.to_time.iso8601,
updatedBy: {
name: issuable.last_edited_by.name,
path: user_path(issuable.last_edited_by)
}
}
end
def issuables_count_for_state(issuable_type, state, finder: nil)
finder ||= public_send("#{issuable_type}_finder")
cache_key = finder.state_counter_cache_key(state)
@counts ||= {}
@counts[cache_key] ||= Rails.cache.fetch(cache_key, expires_in: 2.minutes) do
finder.count_by_state
end
@counts[cache_key][state]
end
private
def sidebar_gutter_collapsed?
cookies[:collapsed_gutter] == 'true'
end
def base_issuable_scope(issuable)
issuable.project.send(issuable.class.table_name).send(issuable_state_scope(issuable))
end
def issuable_state_scope(issuable)
if issuable.respond_to?(:merged?) && issuable.merged?
:merged
else
issuable.open? ? :opened : :closed
end
end
def issuable_templates(issuable)
@issuable_templates ||=
case issuable
when Issue
issue_template_names
when MergeRequest
merge_request_template_names
else
raise 'Unknown issuable type!'
end
end
def merge_request_template_names
@merge_request_templates ||= Gitlab::Template::MergeRequestTemplate.dropdown_names(ref_project)
end
def issue_template_names
@issue_templates ||= Gitlab::Template::IssueTemplate.dropdown_names(ref_project)
end
def selected_template(issuable)
params[:issuable_template] if issuable_templates(issuable).any?{ |template| template[:name] == params[:issuable_template] }
end
def issuable_todo_button_data(issuable, todo, is_collapsed)
{
todo_text: "Add todo",
mark_text: "Mark done",
todo_icon: (is_collapsed ? icon('plus-square') : nil),
mark_icon: (is_collapsed ? icon('check-square', class: 'todo-undone') : nil),
issuable_id: issuable.id,
issuable_type: issuable.class.name.underscore,
url: namespace_project_todos_path(@project.namespace, @project),
delete_path: (dashboard_todo_path(todo) if todo),
placement: (is_collapsed ? 'left' : nil),
container: (is_collapsed ? 'body' : nil)
}
end
end
|
require 'xmlsimple'
module PlatformsHelper
def fetch_all_platforms
xml = open('http://thegamesdb.net/api/GetPlatformsList.php')
platform_data = XmlSimple.xml_in(xml, { 'KeyAttr' => 'Platforms' })["Platforms"].first["Platform"]
platforms = []
platform_data.each do |platform|
puts platform
platforms << build_platform_from_hash(platform)
end
platforms
end
def fetch_platform(platform_id)
xml = open('http://thegamesdb.net/api/GetPlatform.php?id=' + platform_id)
platform_data = XmlSimple.xml_in(xml, { 'KeyAttr' => 'Data' })['Platform'].first
platform = build_platform_from_hash(platform_data)
platform
end
def build_platform_from_hash(platform_hash)
id = platform_hash["id"]
name = platform_hash["name"]
if (name == nil)
name = platform_hash["Platform"]
end
overview = platform_hash["overview"]
developer = platform_hash["developer"]
rating = platform_hash["Rating"]
if Platform.where(:external_id => id.first).exists?
platform = Platform.find_by_external_id(id.first)
else
platform = Platform.create
platform.external_id = id.first;
end
if (name)
platform.name = name.first
end
if (overview)
platform.overview = overview.first
end
if (developer)
platform.developer = developer.first
end
if (rating)
platform.rating = rating.first
end
platform.save
platform
end
end
updated platform
require 'xmlsimple'
module PlatformsHelper
def fetch_all_platforms
xml = open('http://thegamesdb.net/api/GetPlatformsList.php')
platform_data = XmlSimple.xml_in(xml, { 'KeyAttr' => 'Platforms' })["Platforms"].first["Platform"]
platforms = []
platform_data.each do |platform|
puts platform
platforms << build_platform_from_hash(platform)
end
platforms
end
def fetch_platform(platform_id)
xml = open('http://thegamesdb.net/api/GetPlatform.php?id=' + platform_id)
platform_data = XmlSimple.xml_in(xml, { 'KeyAttr' => 'Data' })['Platform'].first
platform = build_platform_from_hash(platform_data)
platform
end
def build_platform_from_hash(platform_hash)
@id = platform_hash["id"]
name = platform_hash["name"]
if (name == nil)
name = platform_hash["Platform"]
end
overview = platform_hash["overview"]
developer = platform_hash["developer"]
rating = platform_hash["Rating"]
if Platform.where(:external_id => @id .first).exists?
platform = Platform.find_by_external_id(@id .first)
else
platform = Platform.new
platform.external_id = @id .first;
end
if (name)
platform.name = name.first
end
if (overview)
platform.overview = overview.first
end
if (developer)
platform.developer = developer.first
end
if (rating)
platform.rating = rating.first
end
platform.save
platform
end
end
|
module RunnablesHelper
def title_text(component, verb, run_as)
text = "#{verb.capitalize} the #{component.class.display_name}: '#{component.name}' as a #{run_as}."
if component.is_a? JnlpLaunchable
text << " The first time you do this it may take a while to startup as the Java code is downloaded and saved on your hard drive."
end
text
end
def run_url_for(component, params = {}, format = nil)
format ||= component.run_format
# this is where we pull in extra parameters for the url, like use_installer
params.update(current_user.extra_params)
params[:format] = format
polymorphic_url(component, params)
end
def run_button_for(component)
x_button_for(component, "run")
end
def x_button_for(component, verb, image = verb, params = {}, run_as = nil)
unless run_as
run_as = case component
when JnlpLaunchable then "Java Web Start application"
when ExternalActivity then "External Activity"
end
end
classes = "run_link rollover"
if component.is_a? Portal::Offering && !component.external_activity?
classes << ' offering'
end
options = {
:class => classes,
:title => title_text(component, verb, run_as)
}
if component.is_a?(ExternalActivity)
options[:popup] = component.popup
elsif component.is_a?(Portal::Offering) && component.external_activity?
options[:popup] = component.runnable.popup
end
link_button("#{image}.png", run_url_for(component, params), options)
end
def x_link_for(component, verb, as_name = nil, params = {})
link_text = params.delete(:link_text) || "#{verb} "
url = run_url_for(component, params)
run_type = case component
when JnlpLaunchable then "Java Web Start application"
when ExternalActivity then "External Activity"
end
title = title_text(component, verb, run_type)
link_text << " as #{as_name}" if as_name
html_options={}
case component
when Portal::Offering
if component.external_activity?
html_options[:class] = 'run_link'
html_options[:popup] = component.runnable.popup
else
html_options[:class] = 'run_link offering'
end
when ExternalActivity
html_options[:popup] = component.popup
else
html_options[:title] = title
end
if params[:no_button]
link_to(link_text, url, html_options)
else
x_button_for(component, verb) + link_to(link_text, url, html_options)
end
end
def preview_button_for(component, url_params = nil, img = "preview.png", run_as = nil)
x_button_for(component, "preview")
end
def teacher_preview_button_for(component)
x_button_for(component, "preview", "teacher_preview", {:teacher_mode => true}, "Teacher")
end
def preview_link_for(component, as_name = nil, params = {})
x_link_for(component, "preview", as_name, params)
end
def offering_link_for(offering, as_name = nil, params = {})
if offering.resource_page?
link_to "View #{offering.name}", offering.runnable
else
x_link_for(offering, "run", as_name, params)
end
end
def run_link_for(component, as_name = nil, params = {})
if component.kind_of?(Portal::Offering)
offering_link_for(component, nil, {:link_text => "run #{component.name}"})
else
x_link_for(component, "run", as_name, params)
end
end
# TODO: think of a better way
def preview_list_link
if settings_for(:runnable_mime_type) =~ /sparks/i
return external_activity_preview_list_path
end
return investigation_preview_list_path
end
end
Fix typo
module RunnablesHelper
def title_text(component, verb, run_as)
text = "#{verb.capitalize} the #{component.class.display_name}: '#{component.name}' as a #{run_as}."
if component.is_a? JnlpLaunchable
text << " The first time you do this it may take a while to startup as the Java code is downloaded and saved on your hard drive."
end
text
end
def run_url_for(component, params = {}, format = nil)
format ||= component.run_format
# this is where we pull in extra parameters for the url, like use_installer
params.update(current_user.extra_params)
params[:format] = format
polymorphic_url(component, params)
end
def run_button_for(component)
x_button_for(component, "run")
end
def x_button_for(component, verb, image = verb, params = {}, run_as = nil)
unless run_as
run_as = case component
when JnlpLaunchable then "Java Web Start application"
when ExternalActivity then "External Activity"
end
end
classes = "run_link rollover"
if component.is_a?(Portal::Offering) && !(component.external_activity?)
classes << ' offering'
end
options = {
:class => classes,
:title => title_text(component, verb, run_as)
}
if component.is_a?(ExternalActivity)
options[:popup] = component.popup
elsif component.is_a?(Portal::Offering) && component.external_activity?
options[:popup] = component.runnable.popup
end
link_button("#{image}.png", run_url_for(component, params), options)
end
def x_link_for(component, verb, as_name = nil, params = {})
link_text = params.delete(:link_text) || "#{verb} "
url = run_url_for(component, params)
run_type = case component
when JnlpLaunchable then "Java Web Start application"
when ExternalActivity then "External Activity"
end
title = title_text(component, verb, run_type)
link_text << " as #{as_name}" if as_name
html_options={}
case component
when Portal::Offering
if component.external_activity?
html_options[:class] = 'run_link'
html_options[:popup] = component.runnable.popup
else
html_options[:class] = 'run_link offering'
end
when ExternalActivity
html_options[:popup] = component.popup
else
html_options[:title] = title
end
if params[:no_button]
link_to(link_text, url, html_options)
else
x_button_for(component, verb) + link_to(link_text, url, html_options)
end
end
def preview_button_for(component, url_params = nil, img = "preview.png", run_as = nil)
x_button_for(component, "preview")
end
def teacher_preview_button_for(component)
x_button_for(component, "preview", "teacher_preview", {:teacher_mode => true}, "Teacher")
end
def preview_link_for(component, as_name = nil, params = {})
x_link_for(component, "preview", as_name, params)
end
def offering_link_for(offering, as_name = nil, params = {})
if offering.resource_page?
link_to "View #{offering.name}", offering.runnable
else
x_link_for(offering, "run", as_name, params)
end
end
def run_link_for(component, as_name = nil, params = {})
if component.kind_of?(Portal::Offering)
offering_link_for(component, nil, {:link_text => "run #{component.name}"})
else
x_link_for(component, "run", as_name, params)
end
end
# TODO: think of a better way
def preview_list_link
if settings_for(:runnable_mime_type) =~ /sparks/i
return external_activity_preview_list_path
end
return investigation_preview_list_path
end
end
|
module ScorebookHelper
def percentage_color(score)
return 'gray' unless score
score = score.to_f / 100.0 if score > 1
score = score.round(2)
case score
when 0.76..1.0
'green'
when 0.5..0.75
'orange'
when 0.0..0.49
'red'
else
'gray'
end
end
def icon_for_classification(classification)
case classification.key
when 'story'
'flag'
when 'practice_question_set'
'puzzle'
else
''
end
end
def icon_for_classification_by_id(activity_classification_id)
case activity_classification_id
when 1
'flag'
when 2
'puzzle'
else
''
end
end
def image_for_activity_classification_by_id(activity_classification_id)
case activity_classification_id
when 1
'scorebook/icon-flag-gray.png'
when 2
'scorebook/icon-puzzle-gray.png'
else
''
end
end
def scorebook_path(teacher)
if teacher.has_classrooms?
scorebook_teachers_classrooms_path
else
''
end
end
def alias_by_id id
case id
when 1
'Quill Proofreader'
when 2
'Quill Grammar'
end
end
def activity_planner_tooltip_html activity_hash # note: not an active record object, a hash
activity_name = activity_hash['activity_name'].nil? ? '' : ("<h1>" + (activity_hash['activity_name'].gsub(/"/, '"')) + "</h1>")
activity_description = activity_hash['activity_description'].nil? ? '' : ("<p>" + (activity_hash['activity_description'].gsub(/"/, '"')) + "</p>")
app_name = activity_hash['activity_classification_name'].nil? ? '' : ("<p> App: " + (activity_hash['activity_classification_name'].gsub(/"/, '"')) + "</p>")
%Q(data-toggle="tooltip" data-html=true data-placement="left" title="#{activity_name}#{app_name}#{activity_description}").html_safe
end
def activity_icon_with_tooltip(activity, activity_session, include_activity_title: false)
#activity, session = activity_and_session(activity_or_session)
render partial: 'activity_icon_with_tooltip', locals: {
activity: activity,
activity_session: activity_session,
include_activity_title: include_activity_title
}
end
# Return both the activity and its session (if there is one)
def activity_and_session(activity_or_session)
if activity_or_session.respond_to?(:activity)
[activity_or_session.activity, activity_or_session]
else
[activity_or_session, nil]
end
end
end
change scorebook_helper method so the if condition is based on classification.id instead of classification.key
module ScorebookHelper
def percentage_color(score)
return 'gray' unless score
score = score.to_f / 100.0 if score > 1
score = score.round(2)
case score
when 0.76..1.0
'green'
when 0.5..0.75
'orange'
when 0.0..0.49
'red'
else
'gray'
end
end
def icon_for_classification(classification)
case classification.id
when 1
'flag'
when 2
'puzzle'
else
''
end
end
def icon_for_classification_by_id(activity_classification_id)
case activity_classification_id
when 1
'flag'
when 2
'puzzle'
else
''
end
end
def image_for_activity_classification_by_id(activity_classification_id)
case activity_classification_id
when 1
'scorebook/icon-flag-gray.png'
when 2
'scorebook/icon-puzzle-gray.png'
else
''
end
end
def scorebook_path(teacher)
if teacher.has_classrooms?
scorebook_teachers_classrooms_path
else
''
end
end
def alias_by_id id
case id
when 1
'Quill Proofreader'
when 2
'Quill Grammar'
end
end
def activity_planner_tooltip_html activity_hash # note: not an active record object, a hash
activity_name = activity_hash['activity_name'].nil? ? '' : ("<h1>" + (activity_hash['activity_name'].gsub(/"/, '"')) + "</h1>")
activity_description = activity_hash['activity_description'].nil? ? '' : ("<p>" + (activity_hash['activity_description'].gsub(/"/, '"')) + "</p>")
app_name = activity_hash['activity_classification_name'].nil? ? '' : ("<p> App: " + (activity_hash['activity_classification_name'].gsub(/"/, '"')) + "</p>")
%Q(data-toggle="tooltip" data-html=true data-placement="left" title="#{activity_name}#{app_name}#{activity_description}").html_safe
end
def activity_icon_with_tooltip(activity, activity_session, include_activity_title: false)
#activity, session = activity_and_session(activity_or_session)
render partial: 'activity_icon_with_tooltip', locals: {
activity: activity,
activity_session: activity_session,
include_activity_title: include_activity_title
}
end
# Return both the activity and its session (if there is one)
def activity_and_session(activity_or_session)
if activity_or_session.respond_to?(:activity)
[activity_or_session.activity, activity_or_session]
else
[activity_or_session, nil]
end
end
end
|
# Scrapes data for Repositories and Users on Github.com
class GithubRepoScraper
SECONDS_BETWEEN_REQUESTS = 0
BASE_URL = "https://github.com"
@github_doc = NokoDoc.new
@current_repo = nil
@commits_created_this_session = 0
@start_time = Time.now
# Commits that will be bulk imported
@stashed_commits = []
# TODO: Investigate and add error handling for 404/500 from github so the error
# is logged but doesn't just crash
# TODO: add check so that these methods don't necessarily take and active record
# model, because we don't want to hit the db everytime in the dispatcher
# TODO: we could pass in a shallow repository model and only actually find the model
# if we need to associate a commit, or actually do an update etc.
# TODO: We should probably check yesterdays commits when we scrape commits to
# make sure we didn’t miss any. There is a chance that in the last 8 hours of
# the day, if there is a commit we won’t get it.
# TODO: Add a column for the *day* the commits were pushed to github and modify
# the scraper to get this data
class << self
# Gets the following:
# - number of stars the project has
# - raw README.md file
#
# Example project's Github url vs raw url
# - Github: https://github.com/rspec/rspec/blob/master/README.md
# - Raw: https://raw.githubusercontent.com/rspec/rspec/master/README.md
def update_repo_data(repos = Repository.all)
repos.each do |repo|
begin
break unless get_repo_doc(repo)
# TODO: add to update_repo_data to get repo name and owner name
# owner, repo_name = @current_repo.url[/\/\w+\/\w+/].split('/)
update_repo_meta(false)
puts "Updated repo #{@current_repo.name}"
rescue OpenURI::HTTPError => e
repo.destroy
puts "DESTROYED #{@current_repo.name} : its Github URL #{@current_repo.url} resulted in #{e.message}"
end
end
end
# Retrieves the open issues and comments for each repository
def issues(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
@repositories.each do |repo|
break unless get_repo_doc(repo, "/issues")
update_repo_meta if get_repo_meta
puts "Scraping issues for #{repo.name}"
issues = [] # cache issues so we can cycle through without hitting the db
loop do
# Get all the issues from page
raw_issues = @github_doc.doc.css("div.issues-listing ul li div.d-table")
raw_issues.each do |raw_issue|
issue = Issue.create( build_issue(raw_issue) )
puts "Creating Issue" if issue.id
issues << issue
end
next_url_anchor = @github_doc.doc.css("a.next_page")
if next_url_anchor.present?
next_url_rel_path = next_url_anchor.attribute("href").value
break unless @github_doc.new_doc(BASE_URL + next_url_rel_path)
else
break
end
end
# Get all the comments for each issue
issues.each do |issue|
doc_path = BASE_URL + issue.url
next unless @github_doc.new_doc(doc_path)
raw_comments = @github_doc.doc.css("div.timeline-comment-wrapper")
raw_comments.each do |raw_comment|
comment_json = build_comment(raw_comment)
comment_json['issue_id'] = issue.id
issue_comment = IssueComment.create(comment_json)
puts "Creating Issue Comment" if issue_comment
end
end
end
end
# Retrieves the commits for each Repository
#
# NOTE: you can use all options together, but whichever one ends first
# will be the one that stops the scraper
#
# Options
# repositories: repos to be scraped for data
# page_limit: maximum number of pages to iterate
# user_limit: max number of users to add
def commits(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
catch :scrape_limit_reached do
@repositories.each do |repo|
break unless get_repo_doc(repo, "/commits")
update_repo_meta if get_repo_meta
puts "Scraping #{repo.name} commits"
catch :recent_commits_finished do
traverse_commit_pagination
end
end
end
end
private
# TODO: we should cache all the users for a repo when a repo is requested, so
# we don't have to hit the DB as often, because I'll have to get the name
# of the user from the comment, search if it exist, then create it.
# If we had them cached I could search those, if not found, create it.
# Basically let's make that query when we get the repo.
def build_comment(raw_comment)
user_name = raw_comment.css("a.author").text
user = User.find_by(github_username: user_name)
unless user
puts "Creating new user: #{user_name}"
user = User.create(github_username: user_name)
end
comment_json = {}
comment_json['user_id'] = user.id
comment_json['github_created_at'] = raw_comment.css("a relative-time").attribute("datetime").value
comment_json['body'] = raw_comment.css("td.comment-body").text
comment_json
end
def build_issue(raw_issue)
issue = {}
issue['repository_id'] = @current_repo.id
issue['name'] = raw_issue.css("a.h4").text.strip
issue['creator'] = raw_issue.css("a.h4")
issue['url'] = raw_issue.css("a.h4").attribute("href").value
issue_number, open_date, creator = raw_issue.css("span.opened-by").text.strip.split("\n")
issue['issue_number'] = issue_number[1..-1].to_i
issue['creator'] = creator.strip
issue['open_date'] = open_date.split(" ")[1..-2].join(" ")
issue
end
def get_repo_doc(repo, path="")
@current_repo = repo
# TODO: consider making a psuedo object to pass around
doc_path = @current_repo.url + path
return @github_doc.new_doc(doc_path)
end
def update_repo_meta(get_readme = false)
# TODO: this isn't working rigt now... fix so we grab the readme
if get_readme
readme_content = repo_readme_content
else
readme_content = nil
end
# Grab general meta data that is available on the commits page
# if told to do so
@current_repo.update(
watchers: repo_watchers,
stars: repo_stars,
forks: repo_forks,
open_issues: repo_open_issues,
readme_content: readme_content
)
end
# this can be added to the other scraper
def handle_scrape_limits(opts={})
@repositories = opts[:repositories] || Repository.all
@page_limit = opts[:page_limit] || Float::INFINITY
@user_limit = opts[:user_limit] || Float::INFINITY
end
def traverse_commit_pagination
page_count = 1
loop do
fetch_commit_data
throw :scrape_limit_reached if page_count >= @page_limit
break unless @github_doc.doc.css('.pagination').any?
page_count += 1
next_path = @github_doc.doc.css('.pagination a')[0]['href']
sleep SECONDS_BETWEEN_REQUESTS
break unless @github_doc.new_doc(BASE_URL + next_path)
end
end
def fetch_commit_data
@github_doc.doc.css('.commit').each do |commit_info|
relative_time = commit_info.css('relative-time')
next if relative_time.empty?
commit_date = Time.parse(relative_time[0][:datetime])
throw :recent_commits_finished unless commit_date.to_date >= last_90_days # for today: commit_date.today?
# Not all avatars are users
user_anchor = commit_info.css('.commit-avatar-cell a')[0]
github_username = user_anchor['href'][1..-1] if user_anchor
if !github_username.nil?
user = User.find_or_create_by(github_username: github_username)
end
if user
message = commit_info.css("a.message").text
github_identifier = commit_info.css("a.sha").text.strip
github_created_at = DateTime.parse(commit_info.css("relative-time").first['datetime'])
@stashed_commits.push Commit.new({
message: message,
user: user,
repository: @current_repo,
github_identifier: github_identifier,
github_created_at: github_created_at
})
if @stashed_commits.count >= 30
@commits_created_this_session += 30
Commit.import(@stashed_commits)
@stashed_commits.clear
puts "Commits cretaed this session: #{@commits_created_this_session}"
puts "Total time so far: #{((Time.now - @start_time) / 60).round(2)}"
end
end
throw :scrape_limit_reached if User.count >= @user_limit
end
end
def last_years_time
DateTime.now - 365
end
def last_90_days
DateTime.now - 90
end
def repo_readme_content
# NOTE: Only available on the code subpage of the repo
if @github_doc.doc.at('td span:contains("README")')
raw_file_url = @current_repo.url.gsub('github', 'raw.githubusercontent' +
'/master/README.md')
NokoDoc.new_temp_doc(raw_file_url).css('body p').text
else
nil
end
end
def select_social_count(child=nil)
@github_doc.doc.css("ul.pagehead-actions li:nth-child(#{child}) .social-count")
.text.strip.gsub(',', '').to_i
end
def repo_watchers
select_social_count(1)
end
def repo_stars
select_social_count(2)
end
def repo_forks
select_social_count(3)
end
def repo_open_issues
@github_doc.doc.css("a.reponav-item span:nth-child(2).counter").text.to_i
end
end
end
added todo
# Scrapes data for Repositories and Users on Github.com
class GithubRepoScraper
SECONDS_BETWEEN_REQUESTS = 0
BASE_URL = "https://github.com"
@github_doc = NokoDoc.new
@current_repo = nil
@commits_created_this_session = 0
@start_time = Time.now
# Commits that will be bulk imported
@stashed_commits = []
# TODO: Investigate and add error handling for 404/500 from github so the error
# is logged but doesn't just crash
# TODO: add check so that these methods don't necessarily take and active record
# model, because we don't want to hit the db everytime in the dispatcher
# TODO: we could pass in a shallow repository model and only actually find the model
# if we need to associate a commit, or actually do an update etc.
# TODO: We should probably check yesterdays commits when we scrape commits to
# make sure we didn’t miss any. There is a chance that in the last 8 hours of
# the day, if there is a commit we won’t get it.
# TODO: Add a column for the *day* the commits were pushed to github and modify
# the scraper to get this data
class << self
# Gets the following:
# - number of stars the project has
# - raw README.md file
#
# Example project's Github url vs raw url
# - Github: https://github.com/rspec/rspec/blob/master/README.md
# - Raw: https://raw.githubusercontent.com/rspec/rspec/master/README.md
def update_repo_data(repos = Repository.all)
repos.each do |repo|
begin
break unless get_repo_doc(repo)
# TODO: add to update_repo_data to get repo name and owner name
# owner, repo_name = @current_repo.url[/\/\w+\/\w+/].split('/)
update_repo_meta(false)
puts "Updated repo #{@current_repo.name}"
rescue OpenURI::HTTPError => e
repo.destroy
puts "DESTROYED #{@current_repo.name} : its Github URL #{@current_repo.url} resulted in #{e.message}"
end
end
end
# Retrieves the open issues and comments for each repository
def issues(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
@repositories.each do |repo|
break unless get_repo_doc(repo, "/issues")
update_repo_meta if get_repo_meta
puts "Scraping issues for #{repo.name}"
issues = [] # cache issues so we can cycle through without hitting the db
loop do
# Get all the issues from page
raw_issues = @github_doc.doc.css("div.issues-listing ul li div.d-table")
raw_issues.each do |raw_issue|
issue = Issue.create( build_issue(raw_issue) )
puts "Creating Issue" if issue.id
issues << issue
end
next_url_anchor = @github_doc.doc.css("a.next_page")
if next_url_anchor.present?
next_url_rel_path = next_url_anchor.attribute("href").value
break unless @github_doc.new_doc(BASE_URL + next_url_rel_path)
else
break
end
end
# Get all the comments for each issue
issues.each do |issue|
doc_path = BASE_URL + issue.url
next unless @github_doc.new_doc(doc_path)
raw_comments = @github_doc.doc.css("div.timeline-comment-wrapper")
raw_comments.each do |raw_comment|
comment_json = build_comment(raw_comment)
comment_json['issue_id'] = issue.id
issue_comment = IssueComment.create(comment_json)
puts "Creating Issue Comment" if issue_comment
end
end
end
end
# Retrieves the commits for each Repository
#
# NOTE: you can use all options together, but whichever one ends first
# will be the one that stops the scraper
#
# Options
# repositories: repos to be scraped for data
# page_limit: maximum number of pages to iterate
# user_limit: max number of users to add
def commits(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
catch :scrape_limit_reached do
@repositories.each do |repo|
break unless get_repo_doc(repo, "/commits")
update_repo_meta if get_repo_meta
puts "Scraping #{repo.name} commits"
catch :recent_commits_finished do
traverse_commit_pagination
end
end
end
end
private
# TODO: we should cache all the users for a repo when a repo is requested, so
# we don't have to hit the DB as often, because I'll have to get the name
# of the user from the comment, search if it exist, then create it.
# If we had them cached I could search those, if not found, create it.
# Basically let's make that query when we get the repo.
def build_comment(raw_comment)
user_name = raw_comment.css("a.author").text
user = User.find_by(github_username: user_name) # TODO: use create! and if it fails, a rescue and find ?
unless user
puts "Creating new user: #{user_name}"
user = User.create(github_username: user_name)
end
comment_json = {}
comment_json['user_id'] = user.id
comment_json['github_created_at'] = raw_comment.css("a relative-time").attribute("datetime").value
comment_json['body'] = raw_comment.css("td.comment-body").text
comment_json
end
def build_issue(raw_issue)
issue = {}
issue['repository_id'] = @current_repo.id
issue['name'] = raw_issue.css("a.h4").text.strip
issue['creator'] = raw_issue.css("a.h4")
issue['url'] = raw_issue.css("a.h4").attribute("href").value
issue_number, open_date, creator = raw_issue.css("span.opened-by").text.strip.split("\n")
issue['issue_number'] = issue_number[1..-1].to_i
issue['creator'] = creator.strip
issue['open_date'] = open_date.split(" ")[1..-2].join(" ")
issue
end
def get_repo_doc(repo, path="")
@current_repo = repo
# TODO: consider making a psuedo object to pass around
doc_path = @current_repo.url + path
return @github_doc.new_doc(doc_path)
end
def update_repo_meta(get_readme = false)
# TODO: this isn't working rigt now... fix so we grab the readme
if get_readme
readme_content = repo_readme_content
else
readme_content = nil
end
# Grab general meta data that is available on the commits page
# if told to do so
@current_repo.update(
watchers: repo_watchers,
stars: repo_stars,
forks: repo_forks,
open_issues: repo_open_issues,
readme_content: readme_content
)
end
# this can be added to the other scraper
def handle_scrape_limits(opts={})
@repositories = opts[:repositories] || Repository.all
@page_limit = opts[:page_limit] || Float::INFINITY
@user_limit = opts[:user_limit] || Float::INFINITY
end
def traverse_commit_pagination
page_count = 1
loop do
fetch_commit_data
throw :scrape_limit_reached if page_count >= @page_limit
break unless @github_doc.doc.css('.pagination').any?
page_count += 1
next_path = @github_doc.doc.css('.pagination a')[0]['href']
sleep SECONDS_BETWEEN_REQUESTS
break unless @github_doc.new_doc(BASE_URL + next_path)
end
end
def fetch_commit_data
@github_doc.doc.css('.commit').each do |commit_info|
relative_time = commit_info.css('relative-time')
next if relative_time.empty?
commit_date = Time.parse(relative_time[0][:datetime])
throw :recent_commits_finished unless commit_date.to_date >= last_90_days # for today: commit_date.today?
# Not all avatars are users
user_anchor = commit_info.css('.commit-avatar-cell a')[0]
github_username = user_anchor['href'][1..-1] if user_anchor
if !github_username.nil?
user = User.find_or_create_by(github_username: github_username)
end
if user
message = commit_info.css("a.message").text
github_identifier = commit_info.css("a.sha").text.strip
github_created_at = DateTime.parse(commit_info.css("relative-time").first['datetime'])
@stashed_commits.push Commit.new({
message: message,
user: user,
repository: @current_repo,
github_identifier: github_identifier,
github_created_at: github_created_at
})
if @stashed_commits.count >= 30
@commits_created_this_session += 30
Commit.import(@stashed_commits)
@stashed_commits.clear
puts "Commits cretaed this session: #{@commits_created_this_session}"
puts "Total time so far: #{((Time.now - @start_time) / 60).round(2)}"
end
end
throw :scrape_limit_reached if User.count >= @user_limit
end
end
def last_years_time
DateTime.now - 365
end
def last_90_days
DateTime.now - 90
end
def repo_readme_content
# NOTE: Only available on the code subpage of the repo
if @github_doc.doc.at('td span:contains("README")')
raw_file_url = @current_repo.url.gsub('github', 'raw.githubusercontent' +
'/master/README.md')
NokoDoc.new_temp_doc(raw_file_url).css('body p').text
else
nil
end
end
def select_social_count(child=nil)
@github_doc.doc.css("ul.pagehead-actions li:nth-child(#{child}) .social-count")
.text.strip.gsub(',', '').to_i
end
def repo_watchers
select_social_count(1)
end
def repo_stars
select_social_count(2)
end
def repo_forks
select_social_count(3)
end
def repo_open_issues
@github_doc.doc.css("a.reponav-item span:nth-child(2).counter").text.to_i
end
end
end
|
# Scrapes data for Repositories and Users on Github.com
class GithubRepoScraper
SECONDS_BETWEEN_REQUESTS = 0
BASE_URL = "https://github.com"
@github_doc = NokoDoc.new
@current_repo = nil
@commits_created_this_session = 0
@start_time = Time.now
# TODO: Investigate and add error handling for 404/500 from github so the error
# is logged but doesn't just crash
# TODO: add check so that these methods don't necessarily take and active record
# model, because we don't want to hit the db everytime in the dispatcher
# TODO: we could pass in a shallow repository model and only actually find the model
# if we need to associate a commit, or actually do an update etc.
# TODO: We should probably check yesterdays commits when we scrape commits to
# make sure we didn’t miss any. There is a chance that in the last 8 hours of
# the day, if there is a commit we won’t get it.
# TODO: Add a column for the *day* the commits were pushed to github and modify
# the scraper to get this data
class << self
# Gets the following:
# - number of stars the project has
# - raw README.md file
#
# Example project's Github url vs raw url
# - Github: https://github.com/rspec/rspec/blob/master/README.md
# - Raw: https://raw.githubusercontent.com/rspec/rspec/master/README.md
def update_repo_data(repos = Repository.all)
repos.each do |repo|
begin
break unless get_repo_doc(repo)
# TODO: add to update_repo_data to get repo name and owner name
# owner, repo_name = @current_repo.url[/\/\w+\/\w+/].split('/)
update_repo_meta(false)
puts "Updated repo #{@current_repo.name}"
rescue OpenURI::HTTPError => e
repo.destroy
puts "DESTROYED #{@current_repo.name} : its Github URL #{@current_repo.url} resulted in #{e.message}"
end
end
end
# Retrieves the open issues and comments for each repository
def issues(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
@repositories.each do |repo|
break unless get_repo_doc(repo, "/issues")
update_repo_meta if get_repo_meta
puts "Scraping issues for #{repo.name}"
issues = [] # cache issues so we can cycle through without hitting the db
loop do
# Get all the issues from page
raw_issues = @github_doc.doc.css("div.issues-listing ul li div.d-table")
raw_issues.each do |raw_issue|
issue = Issue.create( build_issue(raw_issue) )
puts "Creating Issue" if issue.id
issues << issue
end
next_url_anchor = @github_doc.doc.css("a.next_page")
if next_url_anchor.present?
next_url_rel_path = next_url_anchor.attribute("href").value
@github_doc.new_doc(BASE_URL + next_url_rel_path)
else
break
end
end
# Get all the comments for each issue
issues.each do |issue|
doc_path = BASE_URL + issue.url
@github_doc.new_doc(doc_path)
raw_comments = @github_doc.doc.css("div.timeline-comment-wrapper")
raw_comments.each do |raw_comment|
comment_json = build_comment(raw_comment)
comment_json['issue_id'] = issue
issue_comment = IssueComment.create(comment_json)
puts "Creating Issue Comment" if issue_comment
end
end
end
end
# Retrieves the commits for each Repository
#
# NOTE: you can use all options together, but whichever one ends first
# will be the one that stops the scraper
#
# Options
# repositories: repos to be scraped for data
# page_limit: maximum number of pages to iterate
# user_limit: max number of users to add
def commits(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
catch :scrape_limit_reached do
@repositories.each do |repo|
break unless get_repo_doc(repo, "/commits")
update_repo_meta if get_repo_meta
puts "Scraping #{repo.name} commits"
catch :recent_commits_finished do
traverse_commit_pagination
end
end
end
end
private
# TODO: we should cache all the users for a repo when a repo is requested, so
# we don't have to hit the DB as often, because I'll have to get the name
# of the user from the comment, search if it exist, then create it.
# If we had them cached I could search those, if not found, create it.
# Basically let's make that query when we get the repo.
def build_comment(raw_comment)
user_name = raw_comment.css("a.author").text
user = User.find_by(github_username: user_name)
unless user
puts "Creating new user: #{user_name}"
user = User.create(github_username: user_name)
end
comment_json = {}
comment_json['user_id'] = user.id
comment_json['github_created_at'] = raw_comment.css("a relative-time").attribute("datetime").value
comment_json['body'] = raw_comment.css("td.comment-body").text
comment_json
end
def build_issue(raw_issue)
issue = {}
issue['repository_id'] = @current_repo.id
issue['name'] = raw_issue.css("a.h4").text.strip
issue['creator'] = raw_issue.css("a.h4")
issue['url'] = raw_issue.css("a.h4").attribute("href").value
issue_number, open_date, creator = raw_issue.css("span.opened-by").text.strip.split("\n")
issue['issue_number'] = issue_number[1..-1].to_i
issue['creator'] = creator.strip
issue['open_date'] = open_date.split(" ")[1..-2].join(" ")
issue
end
def get_repo_doc(repo, path="")
@current_repo = repo
# TODO: consider making a psuedo object to pass around
doc_path = @current_repo.url + path
binding.pry
return @github_doc.new_doc(doc_path)
end
def update_repo_meta(get_readme = false)
# TODO: this isn't working rigt now... fix so we grab the readme
if get_readme
readme_content = repo_readme_content
else
readme_content = nil
end
# Grab general meta data that is available on the commits page
# if told to do so
@current_repo.update(
watchers: repo_watchers,
stars: repo_stars,
forks: repo_forks,
open_issues: repo_open_issues,
readme_content: readme_content
)
end
# this can be added to the other scraper
def handle_scrape_limits(opts={})
@repositories = opts[:repositories] || Repository.all
@page_limit = opts[:page_limit] || Float::INFINITY
@user_limit = opts[:user_limit] || Float::INFINITY
end
def traverse_commit_pagination
page_count = 1
loop do
fetch_commit_data
throw :scrape_limit_reached if page_count >= @page_limit
break unless @github_doc.doc.css('.pagination').any?
page_count += 1
next_path = @github_doc.doc.css('.pagination a')[0]['href']
sleep SECONDS_BETWEEN_REQUESTS
break unless @github_doc.new_doc(BASE_URL + next_path)
end
end
def fetch_commit_data
@github_doc.doc.css('.commit').each do |commit_info|
commit_date = Time.parse(commit_info.css('relative-time')[0][:datetime])
throw :recent_commits_finished unless commit_date.today?
# Not all avatars are users
user_anchor = commit_info.css('.commit-avatar-cell a')[0]
github_username = user_anchor['href'][1..-1] if user_anchor
if !github_username.nil? && !User.exists?(github_username: github_username)
user = User.create(github_username: github_username)
puts "User CREATE github_username:#{user.github_username}"
elsif !github_username.nil?
user = User.find_by(github_username: github_username)
end
if user
message = commit_info.css("a.message").text
github_identifier = commit_info.css("a.sha").text.strip
github_created_at = DateTime.parse(commit_info.css("relative-time").first['datetime'])
unless Commit.exists?(github_identifier: github_identifier)
Commit.create(
message: message,
user: user,
repository: @current_repo,
github_identifier: github_identifier,
github_created_at: github_created_at
)
@commits_created_this_session += 1
puts "Commit CREATE identifier:#{github_identifier} by #{user.github_username}"
puts "Commits cretaed this session: #{@commits_created_this_session}"
puts "Total time so far: #{((Time.now - @start_time) / 60).round(2)}"
end
end
throw :scrape_limit_reached if User.count >= @user_limit
end
end
def repo_readme_content
# NOTE: Only available on the code subpage of the repo
if @github_doc.doc.at('td span:contains("README")')
raw_file_url = @current_repo.url.gsub('github', 'raw.githubusercontent' +
'/master/README.md')
NokoDoc.new_temp_doc(raw_file_url).css('body p').text
else
nil
end
end
def select_social_count(child=nil)
@github_doc.doc.css("ul.pagehead-actions li:nth-child(#{child}) .social-count")
.text.strip.gsub(',', '').to_i
end
def repo_watchers
select_social_count(1)
end
def repo_stars
select_social_count(2)
end
def repo_forks
select_social_count(3)
end
def repo_open_issues
@github_doc.doc.css("a.reponav-item span:nth-child(2).counter").text.to_i
end
end
end
removed a binding.pry...
# Scrapes data for Repositories and Users on Github.com
class GithubRepoScraper
SECONDS_BETWEEN_REQUESTS = 0
BASE_URL = "https://github.com"
@github_doc = NokoDoc.new
@current_repo = nil
@commits_created_this_session = 0
@start_time = Time.now
# TODO: Investigate and add error handling for 404/500 from github so the error
# is logged but doesn't just crash
# TODO: add check so that these methods don't necessarily take and active record
# model, because we don't want to hit the db everytime in the dispatcher
# TODO: we could pass in a shallow repository model and only actually find the model
# if we need to associate a commit, or actually do an update etc.
# TODO: We should probably check yesterdays commits when we scrape commits to
# make sure we didn’t miss any. There is a chance that in the last 8 hours of
# the day, if there is a commit we won’t get it.
# TODO: Add a column for the *day* the commits were pushed to github and modify
# the scraper to get this data
class << self
# Gets the following:
# - number of stars the project has
# - raw README.md file
#
# Example project's Github url vs raw url
# - Github: https://github.com/rspec/rspec/blob/master/README.md
# - Raw: https://raw.githubusercontent.com/rspec/rspec/master/README.md
def update_repo_data(repos = Repository.all)
repos.each do |repo|
begin
break unless get_repo_doc(repo)
# TODO: add to update_repo_data to get repo name and owner name
# owner, repo_name = @current_repo.url[/\/\w+\/\w+/].split('/)
update_repo_meta(false)
puts "Updated repo #{@current_repo.name}"
rescue OpenURI::HTTPError => e
repo.destroy
puts "DESTROYED #{@current_repo.name} : its Github URL #{@current_repo.url} resulted in #{e.message}"
end
end
end
# Retrieves the open issues and comments for each repository
def issues(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
@repositories.each do |repo|
break unless get_repo_doc(repo, "/issues")
update_repo_meta if get_repo_meta
puts "Scraping issues for #{repo.name}"
issues = [] # cache issues so we can cycle through without hitting the db
loop do
# Get all the issues from page
raw_issues = @github_doc.doc.css("div.issues-listing ul li div.d-table")
raw_issues.each do |raw_issue|
issue = Issue.create( build_issue(raw_issue) )
puts "Creating Issue" if issue.id
issues << issue
end
next_url_anchor = @github_doc.doc.css("a.next_page")
if next_url_anchor.present?
next_url_rel_path = next_url_anchor.attribute("href").value
@github_doc.new_doc(BASE_URL + next_url_rel_path)
else
break
end
end
# Get all the comments for each issue
issues.each do |issue|
doc_path = BASE_URL + issue.url
@github_doc.new_doc(doc_path)
raw_comments = @github_doc.doc.css("div.timeline-comment-wrapper")
raw_comments.each do |raw_comment|
comment_json = build_comment(raw_comment)
comment_json['issue_id'] = issue
issue_comment = IssueComment.create(comment_json)
puts "Creating Issue Comment" if issue_comment
end
end
end
end
# Retrieves the commits for each Repository
#
# NOTE: you can use all options together, but whichever one ends first
# will be the one that stops the scraper
#
# Options
# repositories: repos to be scraped for data
# page_limit: maximum number of pages to iterate
# user_limit: max number of users to add
def commits(scrape_limit_opts={}, get_repo_meta=false)
handle_scrape_limits(scrape_limit_opts)
catch :scrape_limit_reached do
@repositories.each do |repo|
break unless get_repo_doc(repo, "/commits")
update_repo_meta if get_repo_meta
puts "Scraping #{repo.name} commits"
catch :recent_commits_finished do
traverse_commit_pagination
end
end
end
end
private
# TODO: we should cache all the users for a repo when a repo is requested, so
# we don't have to hit the DB as often, because I'll have to get the name
# of the user from the comment, search if it exist, then create it.
# If we had them cached I could search those, if not found, create it.
# Basically let's make that query when we get the repo.
def build_comment(raw_comment)
user_name = raw_comment.css("a.author").text
user = User.find_by(github_username: user_name)
unless user
puts "Creating new user: #{user_name}"
user = User.create(github_username: user_name)
end
comment_json = {}
comment_json['user_id'] = user.id
comment_json['github_created_at'] = raw_comment.css("a relative-time").attribute("datetime").value
comment_json['body'] = raw_comment.css("td.comment-body").text
comment_json
end
def build_issue(raw_issue)
issue = {}
issue['repository_id'] = @current_repo.id
issue['name'] = raw_issue.css("a.h4").text.strip
issue['creator'] = raw_issue.css("a.h4")
issue['url'] = raw_issue.css("a.h4").attribute("href").value
issue_number, open_date, creator = raw_issue.css("span.opened-by").text.strip.split("\n")
issue['issue_number'] = issue_number[1..-1].to_i
issue['creator'] = creator.strip
issue['open_date'] = open_date.split(" ")[1..-2].join(" ")
issue
end
def get_repo_doc(repo, path="")
@current_repo = repo
# TODO: consider making a psuedo object to pass around
doc_path = @current_repo.url + path
return @github_doc.new_doc(doc_path)
end
def update_repo_meta(get_readme = false)
# TODO: this isn't working rigt now... fix so we grab the readme
if get_readme
readme_content = repo_readme_content
else
readme_content = nil
end
# Grab general meta data that is available on the commits page
# if told to do so
@current_repo.update(
watchers: repo_watchers,
stars: repo_stars,
forks: repo_forks,
open_issues: repo_open_issues,
readme_content: readme_content
)
end
# this can be added to the other scraper
def handle_scrape_limits(opts={})
@repositories = opts[:repositories] || Repository.all
@page_limit = opts[:page_limit] || Float::INFINITY
@user_limit = opts[:user_limit] || Float::INFINITY
end
def traverse_commit_pagination
page_count = 1
loop do
fetch_commit_data
throw :scrape_limit_reached if page_count >= @page_limit
break unless @github_doc.doc.css('.pagination').any?
page_count += 1
next_path = @github_doc.doc.css('.pagination a')[0]['href']
sleep SECONDS_BETWEEN_REQUESTS
break unless @github_doc.new_doc(BASE_URL + next_path)
end
end
def fetch_commit_data
@github_doc.doc.css('.commit').each do |commit_info|
commit_date = Time.parse(commit_info.css('relative-time')[0][:datetime])
throw :recent_commits_finished unless commit_date.today?
# Not all avatars are users
user_anchor = commit_info.css('.commit-avatar-cell a')[0]
github_username = user_anchor['href'][1..-1] if user_anchor
if !github_username.nil? && !User.exists?(github_username: github_username)
user = User.create(github_username: github_username)
puts "User CREATE github_username:#{user.github_username}"
elsif !github_username.nil?
user = User.find_by(github_username: github_username)
end
if user
message = commit_info.css("a.message").text
github_identifier = commit_info.css("a.sha").text.strip
github_created_at = DateTime.parse(commit_info.css("relative-time").first['datetime'])
unless Commit.exists?(github_identifier: github_identifier)
Commit.create(
message: message,
user: user,
repository: @current_repo,
github_identifier: github_identifier,
github_created_at: github_created_at
)
@commits_created_this_session += 1
puts "Commit CREATE identifier:#{github_identifier} by #{user.github_username}"
puts "Commits cretaed this session: #{@commits_created_this_session}"
puts "Total time so far: #{((Time.now - @start_time) / 60).round(2)}"
end
end
throw :scrape_limit_reached if User.count >= @user_limit
end
end
def repo_readme_content
# NOTE: Only available on the code subpage of the repo
if @github_doc.doc.at('td span:contains("README")')
raw_file_url = @current_repo.url.gsub('github', 'raw.githubusercontent' +
'/master/README.md')
NokoDoc.new_temp_doc(raw_file_url).css('body p').text
else
nil
end
end
def select_social_count(child=nil)
@github_doc.doc.css("ul.pagehead-actions li:nth-child(#{child}) .social-count")
.text.strip.gsub(',', '').to_i
end
def repo_watchers
select_social_count(1)
end
def repo_stars
select_social_count(2)
end
def repo_forks
select_social_count(3)
end
def repo_open_issues
@github_doc.doc.css("a.reponav-item span:nth-child(2).counter").text.to_i
end
end
end
|
require_relative 'datashare_document'
class ArresteeTracking < DatashareDocument
include Mongoid::Document
embedded_in :incident
def arrest_id
body["ds:ArresteeTrackingXml"]["j:Arrest"]["nc:ActivityIdentification"]["nc:IdentificationID"]
end
private
def body
self["soapenv:Envelope"]["soapenv:Body"]
end
def header
self["soapenv:Envelope"]["soapenv:Header"]
end
end
Refactor ArresteeTracking.
require_relative 'datashare_document'
class ArresteeTracking < DatashareDocument
include Mongoid::Document
embedded_in :incident
field :arrest_id, type: String
def self.from_xml(xml_string)
importer = XMLDocImporter.new(xml_string, "/soapenv:Envelope/soapenv:Body/ds:ArresteeTrackingXml")
arrestee_trackings = []
arrest_ids = importer.attribute_from_xpath("/j:Arrest/nc:ActivityIdentification/nc:IdentificationID").compact
# TODO: There are separate arrest IDS for ARR_ID and LEAD_ARR_ID. Should we choose one instead of both?
arrest_ids.each do |arrest_id|
at = ArresteeTracking.new
at.arrest_id = arrest_id
at.incident = Incident.find_or_initialize_by(arrest_id: at.arrest_id)
arrestee_trackings << at
end
arrestee_trackings
end
end
|
class Budget
class Investment < ActiveRecord::Base
include Measurable
include Sanitizable
include Taggable
include Searchable
acts_as_votable
acts_as_paranoid column: :hidden_at
include ActsAsParanoidAliases
belongs_to :author, -> { with_hidden }, class_name: 'User', foreign_key: 'author_id'
belongs_to :heading
belongs_to :group
belongs_to :budget
belongs_to :administrator
has_many :valuator_assignments, dependent: :destroy
has_many :valuators, through: :valuator_assignments
has_many :comments, as: :commentable
validates :title, presence: true
validates :author, presence: true
validates :description, presence: true
validates :heading_id, presence: true
validates_presence_of :unfeasibility_explanation, if: :unfeasibility_explanation_required?
validates :title, length: { in: 4 .. Budget::Investment.title_max_length }
validates :description, length: { maximum: Budget::Investment.description_max_length }
validates :terms_of_service, acceptance: { allow_nil: false }, on: :create
scope :sort_by_confidence_score, -> { reorder(confidence_score: :desc, id: :desc) }
scope :sort_by_price, -> { reorder(price: :desc, confidence_score: :desc, id: :desc) }
scope :sort_by_random, -> { reorder("RANDOM()") }
scope :valuation_open, -> { where(valuation_finished: false) }
scope :without_admin, -> { valuation_open.where(administrator_id: nil) }
scope :managed, -> { valuation_open.where(valuator_assignments_count: 0).where("administrator_id IS NOT ?", nil) }
scope :valuating, -> { valuation_open.where("valuator_assignments_count > 0 AND valuation_finished = ?", false) }
scope :valuation_finished, -> { where(valuation_finished: true) }
scope :feasible, -> { where(feasibility: "feasible") }
scope :unfeasible, -> { where(feasibility: "unfeasible") }
scope :not_unfeasible, -> { where.not(feasibility: "unfeasible") }
scope :undecided, -> { where(feasibility: "undecided") }
scope :with_supports, -> { where('cached_votes_up > 0') }
scope :by_group, -> (group_id) { where(group_id: group_id) }
scope :by_heading, -> (heading_id) { where(heading_id: heading_id) }
scope :by_admin, -> (admin_id) { where(administrator_id: admin_id) }
scope :by_tag, -> (tag_name) { tagged_with(tag_name) }
scope :by_valuator, -> (valuator_id) { where("budget_valuator_assignments.valuator_id = ?", valuator_id).joins(:valuator_assignments) }
scope :for_render, -> { includes(heading: :geozone) }
before_save :calculate_confidence_score
before_validation :set_responsible_name
before_validation :set_denormalized_ids
def self.filter_params(params)
params.select{|x,_| %w{heading_id group_id administrator_id tag_name valuator_id}.include? x.to_s }
end
def self.scoped_filter(params, current_filter)
results = Investment.where(budget_id: params[:budget_id])
results = results.where(group_id: params[:group_id]) if params[:group_id].present?
results = results.by_heading(params[:heading_id]) if params[:heading_id].present?
results = results.by_admin(params[:administrator_id]) if params[:administrator_id].present?
results = results.by_tag(params[:tag_name]) if params[:tag_name].present?
results = results.by_valuator(params[:valuator_id]) if params[:valuator_id].present?
results = results.send(current_filter) if current_filter.present?
results.includes(:heading, :group, :budget, administrator: :user, valuators: :user)
end
def self.limit_results(results, budget, max_per_heading, max_for_no_heading)
return results if max_per_heading <= 0 && max_for_no_heading <= 0
ids = []
if max_per_heading > 0
budget.headings.pluck(:id).each do |hid|
ids += Investment.where(heading_id: hid).order(confidence_score: :desc).limit(max_per_heading).pluck(:id)
end
end
if max_for_no_heading > 0
ids += Investment.no_heading.order(confidence_score: :desc).limit(max_for_no_heading).pluck(:id)
end
conditions = ["investments.id IN (?)"]
values = [ids]
if max_per_heading == 0
conditions << "investments.heading_id IS NOT ?"
values << nil
elsif max_for_no_heading == 0
conditions << "investments.heading_id IS ?"
values << nil
end
results.where(conditions.join(' OR '), *values)
end
def searchable_values
{ title => 'A',
author.username => 'B',
heading.try(:name) => 'B',
description => 'C'
}
end
def self.search(terms)
self.pg_search(terms)
end
def self.by_heading(heading)
where(heading_id: heading == 'all' ? nil : heading.presence)
end
def undecided?
feasibility == "undecided"
end
def feasible?
feasibility == "feasible"
end
def unfeasible?
feasibility == "unfeasible"
end
def unfeasibility_explanation_required?
unfeasible? && valuation_finished?
end
def total_votes
cached_votes_up + physical_votes
end
def code
"B#{budget.id}I#{id}"
end
def reason_for_not_being_selectable_by(user)
return permission_problem(user) if permission_problem?(user)
return :no_selecting_allowed unless budget.selecting?
end
def reason_for_not_being_ballotable_by(user, ballot)
return permission_problem(user) if permission_problem?(user)
return :no_ballots_allowed unless budget.balloting?
return :different_heading_assigned unless ballot.valid_heading?(heading)
return :not_enough_money if ballot.present? && !enough_money?(ballot)
end
def permission_problem(user)
return :not_logged_in unless user
return :organization if user.organization?
return :not_verified unless user.can?(:vote, SpendingProposal)
return nil
end
def permission_problem?(user)
permission_problem(user).present?
end
def selectable_by?(user)
reason_for_not_being_selectable_by(user).blank?
end
def ballotable_by?(user)
reason_for_not_being_ballotable_by(user).blank?
end
def enough_money?(ballot)
available_money = ballot.amount_available(self.heading)
price.to_i <= available_money
end
def register_selection(user)
vote_by(voter: user, vote: 'yes') if selectable_by?(user)
end
def calculate_confidence_score
self.confidence_score = ScoreCalculator.confidence_score(total_votes, total_votes)
end
def set_responsible_name
self.responsible_name = author.try(:document_number) if author.try(:document_number).present?
end
def should_show_aside?
(budget.selecting? && !investment.unfeasible?) ||
(budget.balloting? && investment.feasible?) ||
budget.on_hold?
end
def should_show_votes?
budget.selecting? || budget.on_hold?
end
def should_show_ballots?
budget.balloting?
end
def formatted_price
budget.formatted_amount(price)
end
private
def set_denormalized_ids
self.group_id ||= self.heading.group_id
self.budget_id ||= self.heading.group.budget_id
end
end
end
Fixes typo
class Budget
class Investment < ActiveRecord::Base
include Measurable
include Sanitizable
include Taggable
include Searchable
acts_as_votable
acts_as_paranoid column: :hidden_at
include ActsAsParanoidAliases
belongs_to :author, -> { with_hidden }, class_name: 'User', foreign_key: 'author_id'
belongs_to :heading
belongs_to :group
belongs_to :budget
belongs_to :administrator
has_many :valuator_assignments, dependent: :destroy
has_many :valuators, through: :valuator_assignments
has_many :comments, as: :commentable
validates :title, presence: true
validates :author, presence: true
validates :description, presence: true
validates :heading_id, presence: true
validates_presence_of :unfeasibility_explanation, if: :unfeasibility_explanation_required?
validates :title, length: { in: 4 .. Budget::Investment.title_max_length }
validates :description, length: { maximum: Budget::Investment.description_max_length }
validates :terms_of_service, acceptance: { allow_nil: false }, on: :create
scope :sort_by_confidence_score, -> { reorder(confidence_score: :desc, id: :desc) }
scope :sort_by_price, -> { reorder(price: :desc, confidence_score: :desc, id: :desc) }
scope :sort_by_random, -> { reorder("RANDOM()") }
scope :valuation_open, -> { where(valuation_finished: false) }
scope :without_admin, -> { valuation_open.where(administrator_id: nil) }
scope :managed, -> { valuation_open.where(valuator_assignments_count: 0).where("administrator_id IS NOT ?", nil) }
scope :valuating, -> { valuation_open.where("valuator_assignments_count > 0 AND valuation_finished = ?", false) }
scope :valuation_finished, -> { where(valuation_finished: true) }
scope :feasible, -> { where(feasibility: "feasible") }
scope :unfeasible, -> { where(feasibility: "unfeasible") }
scope :not_unfeasible, -> { where.not(feasibility: "unfeasible") }
scope :undecided, -> { where(feasibility: "undecided") }
scope :with_supports, -> { where('cached_votes_up > 0') }
scope :by_group, -> (group_id) { where(group_id: group_id) }
scope :by_heading, -> (heading_id) { where(heading_id: heading_id) }
scope :by_admin, -> (admin_id) { where(administrator_id: admin_id) }
scope :by_tag, -> (tag_name) { tagged_with(tag_name) }
scope :by_valuator, -> (valuator_id) { where("budget_valuator_assignments.valuator_id = ?", valuator_id).joins(:valuator_assignments) }
scope :for_render, -> { includes(heading: :geozone) }
before_save :calculate_confidence_score
before_validation :set_responsible_name
before_validation :set_denormalized_ids
def self.filter_params(params)
params.select{|x,_| %w{heading_id group_id administrator_id tag_name valuator_id}.include? x.to_s }
end
def self.scoped_filter(params, current_filter)
results = Investment.where(budget_id: params[:budget_id])
results = results.where(group_id: params[:group_id]) if params[:group_id].present?
results = results.by_heading(params[:heading_id]) if params[:heading_id].present?
results = results.by_admin(params[:administrator_id]) if params[:administrator_id].present?
results = results.by_tag(params[:tag_name]) if params[:tag_name].present?
results = results.by_valuator(params[:valuator_id]) if params[:valuator_id].present?
results = results.send(current_filter) if current_filter.present?
results.includes(:heading, :group, :budget, administrator: :user, valuators: :user)
end
def self.limit_results(results, budget, max_per_heading, max_for_no_heading)
return results if max_per_heading <= 0 && max_for_no_heading <= 0
ids = []
if max_per_heading > 0
budget.headings.pluck(:id).each do |hid|
ids += Investment.where(heading_id: hid).order(confidence_score: :desc).limit(max_per_heading).pluck(:id)
end
end
if max_for_no_heading > 0
ids += Investment.no_heading.order(confidence_score: :desc).limit(max_for_no_heading).pluck(:id)
end
conditions = ["investments.id IN (?)"]
values = [ids]
if max_per_heading == 0
conditions << "investments.heading_id IS NOT ?"
values << nil
elsif max_for_no_heading == 0
conditions << "investments.heading_id IS ?"
values << nil
end
results.where(conditions.join(' OR '), *values)
end
def searchable_values
{ title => 'A',
author.username => 'B',
heading.try(:name) => 'B',
description => 'C'
}
end
def self.search(terms)
self.pg_search(terms)
end
def self.by_heading(heading)
where(heading_id: heading == 'all' ? nil : heading.presence)
end
def undecided?
feasibility == "undecided"
end
def feasible?
feasibility == "feasible"
end
def unfeasible?
feasibility == "unfeasible"
end
def unfeasibility_explanation_required?
unfeasible? && valuation_finished?
end
def total_votes
cached_votes_up + physical_votes
end
def code
"B#{budget.id}I#{id}"
end
def reason_for_not_being_selectable_by(user)
return permission_problem(user) if permission_problem?(user)
return :no_selecting_allowed unless budget.selecting?
end
def reason_for_not_being_ballotable_by(user, ballot)
return permission_problem(user) if permission_problem?(user)
return :no_ballots_allowed unless budget.balloting?
return :different_heading_assigned unless ballot.valid_heading?(heading)
return :not_enough_money if ballot.present? && !enough_money?(ballot)
end
def permission_problem(user)
return :not_logged_in unless user
return :organization if user.organization?
return :not_verified unless user.can?(:vote, Budget::Investment)
return nil
end
def permission_problem?(user)
permission_problem(user).present?
end
def selectable_by?(user)
reason_for_not_being_selectable_by(user).blank?
end
def ballotable_by?(user)
reason_for_not_being_ballotable_by(user).blank?
end
def enough_money?(ballot)
available_money = ballot.amount_available(self.heading)
price.to_i <= available_money
end
def register_selection(user)
vote_by(voter: user, vote: 'yes') if selectable_by?(user)
end
def calculate_confidence_score
self.confidence_score = ScoreCalculator.confidence_score(total_votes, total_votes)
end
def set_responsible_name
self.responsible_name = author.try(:document_number) if author.try(:document_number).present?
end
def should_show_aside?
(budget.selecting? && !investment.unfeasible?) ||
(budget.balloting? && investment.feasible?) ||
budget.on_hold?
end
def should_show_votes?
budget.selecting? || budget.on_hold?
end
def should_show_ballots?
budget.balloting?
end
def formatted_price
budget.formatted_amount(price)
end
private
def set_denormalized_ids
self.group_id ||= self.heading.group_id
self.budget_id ||= self.heading.group.budget_id
end
end
end
|
require 'csv'
class Budget
class Investment < ActiveRecord::Base
SORTING_OPTIONS = %w(id title supports).freeze
include Rails.application.routes.url_helpers
include Measurable
include Sanitizable
include Taggable
include Searchable
include Reclassification
include Followable
include Communitable
include Imageable
include Mappable
include Documentable
documentable max_documents_allowed: 3,
max_file_size: 3.megabytes,
accepted_content_types: [ "application/pdf" ]
acts_as_votable
acts_as_paranoid column: :hidden_at
include ActsAsParanoidAliases
include Relationable
include Notifiable
include Filterable
belongs_to :author, -> { with_hidden }, class_name: 'User', foreign_key: 'author_id'
belongs_to :heading
belongs_to :group
belongs_to :budget
belongs_to :administrator
has_many :valuator_assignments, dependent: :destroy
has_many :valuators, through: :valuator_assignments
has_many :comments, as: :commentable
has_many :milestones
validates :title, presence: true
validates :author, presence: true
validates :description, presence: true
validates :heading_id, presence: true
validates :unfeasibility_explanation, presence: { if: :unfeasibility_explanation_required? }
validates :price, presence: { if: :price_required? }
validates :title, length: { in: 4..Budget::Investment.title_max_length }
validates :description, length: { maximum: Budget::Investment.description_max_length }
validates :terms_of_service, acceptance: { allow_nil: false }, on: :create
scope :sort_by_confidence_score, -> { reorder(confidence_score: :desc, id: :desc) }
scope :sort_by_ballots, -> { reorder(ballot_lines_count: :desc, id: :desc) }
scope :sort_by_price, -> { reorder(price: :desc, confidence_score: :desc, id: :desc) }
scope :sort_by_random, ->(seed) { reorder("budget_investments.id % #{seed.to_f.nonzero? ? seed.to_f : 1}, budget_investments.id") }
scope :valuation_open, -> { where(valuation_finished: false) }
scope :without_admin, -> { valuation_open.where(administrator_id: nil) }
scope :without_valuator, -> { valuation_open.where(valuator_assignments_count: 0) }
scope :under_valuation, -> { valuation_open.where("valuator_assignments_count > 0 AND administrator_id IS NOT ?", nil) }
scope :managed, -> { valuation_open.where(valuator_assignments_count: 0).where("administrator_id IS NOT ?", nil) }
scope :valuating, -> { valuation_open.where("valuator_assignments_count > 0") }
scope :valuation_finished, -> { where(valuation_finished: true) }
scope :valuation_finished_feasible, -> { where(valuation_finished: true, feasibility: "feasible") }
scope :feasible, -> { where(feasibility: "feasible") }
scope :unfeasible, -> { where(feasibility: "unfeasible") }
scope :not_unfeasible, -> { where.not(feasibility: "unfeasible") }
scope :undecided, -> { where(feasibility: "undecided") }
scope :with_supports, -> { where('cached_votes_up > 0') }
scope :selected, -> { feasible.where(selected: true) }
scope :compatible, -> { where(incompatible: false) }
scope :incompatible, -> { where(incompatible: true) }
scope :winners, -> { selected.compatible.where(winner: true) }
scope :unselected, -> { not_unfeasible.where(selected: false) }
scope :last_week, -> { where("created_at >= ?", 7.days.ago)}
scope :by_group, ->(group_id) { where(group_id: group_id) }
scope :by_heading, ->(heading_id) { where(heading_id: heading_id) }
scope :by_admin, ->(admin_id) { where(administrator_id: admin_id) }
scope :by_tag, ->(tag_name) { tagged_with(tag_name) }
scope :by_valuator, ->(valuator_id) { where("budget_valuator_assignments.valuator_id = ?", valuator_id).joins(:valuator_assignments) }
scope :for_render, -> { includes(:heading) }
before_save :calculate_confidence_score
after_save :recalculate_heading_winners if :incompatible_changed?
before_validation :set_responsible_name
before_validation :set_denormalized_ids
def url
budget_investment_path(budget, self)
end
def self.filter_params(params)
params.select{ |x, _| %w{heading_id group_id administrator_id tag_name valuator_id}.include?(x.to_s) }
end
def self.scoped_filter(params, current_filter)
budget = Budget.find_by(slug: params[:budget_id]) || Budget.find_by(id: params[:budget_id])
results = Investment.where(budget_id: budget.id)
results = limit_results(budget, params, results) if params[:max_per_heading].present?
results = results.where(group_id: params[:group_id]) if params[:group_id].present?
results = results.by_tag(params[:tag_name]) if params[:tag_name].present?
results = results.by_heading(params[:heading_id]) if params[:heading_id].present?
results = results.by_valuator(params[:valuator_id]) if params[:valuator_id].present?
results = results.by_admin(params[:administrator_id]) if params[:administrator_id].present?
# Advanced filters
results = results.valuation_finished_feasible if params[:second_filter] == 'feasible'
results = results.where(selected: true) if params[:second_filter] == 'selected'
results = results.undecided if params[:second_filter] == 'undecided'
results = results.unfeasible if params[:second_filter] == 'unfeasible'
results = results.send(current_filter) if current_filter.present?
results.includes(:heading, :group, :budget, administrator: :user, valuators: :user)
end
def self.limit_results(budget, params, results)
max_per_heading = params[:max_per_heading].to_i
return results if max_per_heading <= 0
ids = []
budget.headings.pluck(:id).each do |hid|
ids += Investment.where(heading_id: hid).order(confidence_score: :desc).limit(max_per_heading).pluck(:id)
end
results.where("budget_investments.id IN (?)", ids)
end
def searchable_values
{ title => 'A',
author.username => 'B',
heading.try(:name) => 'B',
tag_list.join(' ') => 'B',
description => 'C'
}
end
def self.search(terms)
pg_search(terms)
end
def self.by_heading(heading)
where(heading_id: heading == 'all' ? nil : heading.presence)
end
def undecided?
feasibility == "undecided"
end
def feasible?
feasibility == "feasible"
end
def unfeasible?
feasibility == "unfeasible"
end
def unfeasibility_explanation_required?
unfeasible? && valuation_finished?
end
def price_required?
feasible? && valuation_finished?
end
def unfeasible_email_pending?
unfeasible_email_sent_at.blank? && unfeasible? && valuation_finished?
end
def total_votes
cached_votes_up + physical_votes
end
def code
"#{created_at.strftime('%Y')}-#{id}" + (administrator.present? ? "-A#{administrator.id}" : "")
end
def send_unfeasible_email
Mailer.budget_investment_unfeasible(self).deliver_later
update(unfeasible_email_sent_at: Time.current)
end
def reason_for_not_being_selectable_by(user)
return permission_problem(user) if permission_problem?(user)
return :different_heading_assigned unless valid_heading?(user)
return :no_selecting_allowed unless budget.selecting?
end
def reason_for_not_being_ballotable_by(user, ballot)
return permission_problem(user) if permission_problem?(user)
return :not_selected unless selected?
return :no_ballots_allowed unless budget.balloting?
return :different_heading_assigned unless ballot.valid_heading?(heading)
return :not_enough_money_html if ballot.present? && !enough_money?(ballot)
end
def permission_problem(user)
return :not_logged_in unless user
return :organization if user.organization?
return :not_verified unless user.can?(:vote, Budget::Investment)
nil
end
def permission_problem?(user)
permission_problem(user).present?
end
def selectable_by?(user)
reason_for_not_being_selectable_by(user).blank?
end
def valid_heading?(user)
!different_heading_assigned?(user)
end
def different_heading_assigned?(user)
other_heading_ids = group.heading_ids - [heading.id]
voted_in?(other_heading_ids, user)
end
def voted_in?(heading_ids, user)
heading_ids.include? heading_voted_by_user?(user)
end
def heading_voted_by_user?(user)
user.votes.for_budget_investments(budget.investments.where(group: group))
.votables.map(&:heading_id).first
end
def ballotable_by?(user)
reason_for_not_being_ballotable_by(user).blank?
end
def enough_money?(ballot)
available_money = ballot.amount_available(heading)
price.to_i <= available_money
end
def register_selection(user)
vote_by(voter: user, vote: 'yes') if selectable_by?(user)
end
def calculate_confidence_score
self.confidence_score = ScoreCalculator.confidence_score(total_votes, total_votes)
end
def recalculate_heading_winners
Budget::Result.new(budget, heading).calculate_winners if incompatible_changed?
end
def set_responsible_name
self.responsible_name = author.try(:document_number) if author.try(:document_number).present?
end
def should_show_aside?
(budget.selecting? && !unfeasible?) ||
(budget.balloting? && feasible?) ||
(budget.valuating? && !unfeasible?)
end
def should_show_votes?
budget.selecting?
end
def should_show_vote_count?
budget.valuating?
end
def should_show_ballots?
budget.balloting? && selected?
end
def should_show_price?
selected? && price.present? && budget.published_prices?
end
def should_show_price_explanation?
should_show_price? && price_explanation.present?
end
def formatted_price
budget.formatted_amount(price)
end
def self.apply_filters_and_search(_budget, params, current_filter = nil)
investments = all
investments = investments.send(current_filter) if current_filter.present?
investments = investments.by_heading(params[:heading_id]) if params[:heading_id].present?
investments = investments.search(params[:search]) if params[:search].present?
investments = investments.filter(params[:advanced_search]) if params[:advanced_search].present?
investments
end
def self.to_csv(investments, options = {})
attrs = [I18n.t("admin.budget_investments.index.table_id"),
I18n.t("admin.budget_investments.index.table_title"),
I18n.t("admin.budget_investments.index.table_supports"),
I18n.t("admin.budget_investments.index.table_admin"),
I18n.t("admin.budget_investments.index.table_valuator"),
I18n.t("admin.budget_investments.index.table_geozone"),
I18n.t("admin.budget_investments.index.table_feasibility"),
I18n.t("admin.budget_investments.index.table_valuation_finished"),
I18n.t("admin.budget_investments.index.table_selection")]
csv_string = CSV.generate(options) do |csv|
csv << attrs
investments.each do |investment|
id = investment.id.to_s
title = investment.title
total_votes = investment.total_votes.to_s
admin = if investment.administrator.present?
investment.administrator.name
else
I18n.t("admin.budget_investments.index.no_admin_assigned")
end
vals = if investment.valuators.empty?
I18n.t("admin.budget_investments.index.no_valuators_assigned")
else
investment.valuators.collect(&:description_or_name).join(', ')
end
heading_name = investment.heading.name
price_string = "admin.budget_investments.index.feasibility"\
".#{investment.feasibility}"
price = I18n.t(price_string, price: investment.formatted_price)
valuation_finished = investment.valuation_finished? ?
I18n.t('shared.yes') :
I18n.t('shared.no')
csv << [id, title, total_votes, admin, vals, heading_name, price,
valuation_finished]
end
end
csv_string
end
private
def set_denormalized_ids
self.group_id = heading.try(:group_id) if heading_id_changed?
self.budget_id ||= heading.try(:group).try(:budget_id)
end
end
end
Add valuation comments relation at Budget Investment
Why:
Budget Investments already has an existing `comments` relation that is
on use. We need to keep that relation unaltered after adding the
internal valuation comments, that means scoping the relation to only
public comments (non valuation ones) so existing code using it will
remain working as expected.
A new second relation will be needed to explicitly ask for valuation
comments only where needed, again scoping to valuation comments.
How:
Adding a second `valuations` relationship and filtering on both
with the new `valuation` flag from Comment model.
require 'csv'
class Budget
class Investment < ActiveRecord::Base
SORTING_OPTIONS = %w(id title supports).freeze
include Rails.application.routes.url_helpers
include Measurable
include Sanitizable
include Taggable
include Searchable
include Reclassification
include Followable
include Communitable
include Imageable
include Mappable
include Documentable
documentable max_documents_allowed: 3,
max_file_size: 3.megabytes,
accepted_content_types: [ "application/pdf" ]
acts_as_votable
acts_as_paranoid column: :hidden_at
include ActsAsParanoidAliases
include Relationable
include Notifiable
include Filterable
belongs_to :author, -> { with_hidden }, class_name: 'User', foreign_key: 'author_id'
belongs_to :heading
belongs_to :group
belongs_to :budget
belongs_to :administrator
has_many :valuator_assignments, dependent: :destroy
has_many :valuators, through: :valuator_assignments
has_many :comments, -> {where(valuation: false)}, as: :commentable, class_name: 'Comment'
has_many :valuations, -> {where(valuation: true)}, as: :commentable, class_name: 'Comment'
has_many :milestones
validates :title, presence: true
validates :author, presence: true
validates :description, presence: true
validates :heading_id, presence: true
validates :unfeasibility_explanation, presence: { if: :unfeasibility_explanation_required? }
validates :price, presence: { if: :price_required? }
validates :title, length: { in: 4..Budget::Investment.title_max_length }
validates :description, length: { maximum: Budget::Investment.description_max_length }
validates :terms_of_service, acceptance: { allow_nil: false }, on: :create
scope :sort_by_confidence_score, -> { reorder(confidence_score: :desc, id: :desc) }
scope :sort_by_ballots, -> { reorder(ballot_lines_count: :desc, id: :desc) }
scope :sort_by_price, -> { reorder(price: :desc, confidence_score: :desc, id: :desc) }
scope :sort_by_random, ->(seed) { reorder("budget_investments.id % #{seed.to_f.nonzero? ? seed.to_f : 1}, budget_investments.id") }
scope :valuation_open, -> { where(valuation_finished: false) }
scope :without_admin, -> { valuation_open.where(administrator_id: nil) }
scope :without_valuator, -> { valuation_open.where(valuator_assignments_count: 0) }
scope :under_valuation, -> { valuation_open.where("valuator_assignments_count > 0 AND administrator_id IS NOT ?", nil) }
scope :managed, -> { valuation_open.where(valuator_assignments_count: 0).where("administrator_id IS NOT ?", nil) }
scope :valuating, -> { valuation_open.where("valuator_assignments_count > 0") }
scope :valuation_finished, -> { where(valuation_finished: true) }
scope :valuation_finished_feasible, -> { where(valuation_finished: true, feasibility: "feasible") }
scope :feasible, -> { where(feasibility: "feasible") }
scope :unfeasible, -> { where(feasibility: "unfeasible") }
scope :not_unfeasible, -> { where.not(feasibility: "unfeasible") }
scope :undecided, -> { where(feasibility: "undecided") }
scope :with_supports, -> { where('cached_votes_up > 0') }
scope :selected, -> { feasible.where(selected: true) }
scope :compatible, -> { where(incompatible: false) }
scope :incompatible, -> { where(incompatible: true) }
scope :winners, -> { selected.compatible.where(winner: true) }
scope :unselected, -> { not_unfeasible.where(selected: false) }
scope :last_week, -> { where("created_at >= ?", 7.days.ago)}
scope :by_group, ->(group_id) { where(group_id: group_id) }
scope :by_heading, ->(heading_id) { where(heading_id: heading_id) }
scope :by_admin, ->(admin_id) { where(administrator_id: admin_id) }
scope :by_tag, ->(tag_name) { tagged_with(tag_name) }
scope :by_valuator, ->(valuator_id) { where("budget_valuator_assignments.valuator_id = ?", valuator_id).joins(:valuator_assignments) }
scope :for_render, -> { includes(:heading) }
before_save :calculate_confidence_score
after_save :recalculate_heading_winners if :incompatible_changed?
before_validation :set_responsible_name
before_validation :set_denormalized_ids
def url
budget_investment_path(budget, self)
end
def self.filter_params(params)
params.select{ |x, _| %w{heading_id group_id administrator_id tag_name valuator_id}.include?(x.to_s) }
end
def self.scoped_filter(params, current_filter)
budget = Budget.find_by(slug: params[:budget_id]) || Budget.find_by(id: params[:budget_id])
results = Investment.where(budget_id: budget.id)
results = limit_results(budget, params, results) if params[:max_per_heading].present?
results = results.where(group_id: params[:group_id]) if params[:group_id].present?
results = results.by_tag(params[:tag_name]) if params[:tag_name].present?
results = results.by_heading(params[:heading_id]) if params[:heading_id].present?
results = results.by_valuator(params[:valuator_id]) if params[:valuator_id].present?
results = results.by_admin(params[:administrator_id]) if params[:administrator_id].present?
# Advanced filters
results = results.valuation_finished_feasible if params[:second_filter] == 'feasible'
results = results.where(selected: true) if params[:second_filter] == 'selected'
results = results.undecided if params[:second_filter] == 'undecided'
results = results.unfeasible if params[:second_filter] == 'unfeasible'
results = results.send(current_filter) if current_filter.present?
results.includes(:heading, :group, :budget, administrator: :user, valuators: :user)
end
def self.limit_results(budget, params, results)
max_per_heading = params[:max_per_heading].to_i
return results if max_per_heading <= 0
ids = []
budget.headings.pluck(:id).each do |hid|
ids += Investment.where(heading_id: hid).order(confidence_score: :desc).limit(max_per_heading).pluck(:id)
end
results.where("budget_investments.id IN (?)", ids)
end
def searchable_values
{ title => 'A',
author.username => 'B',
heading.try(:name) => 'B',
tag_list.join(' ') => 'B',
description => 'C'
}
end
def self.search(terms)
pg_search(terms)
end
def self.by_heading(heading)
where(heading_id: heading == 'all' ? nil : heading.presence)
end
def undecided?
feasibility == "undecided"
end
def feasible?
feasibility == "feasible"
end
def unfeasible?
feasibility == "unfeasible"
end
def unfeasibility_explanation_required?
unfeasible? && valuation_finished?
end
def price_required?
feasible? && valuation_finished?
end
def unfeasible_email_pending?
unfeasible_email_sent_at.blank? && unfeasible? && valuation_finished?
end
def total_votes
cached_votes_up + physical_votes
end
def code
"#{created_at.strftime('%Y')}-#{id}" + (administrator.present? ? "-A#{administrator.id}" : "")
end
def send_unfeasible_email
Mailer.budget_investment_unfeasible(self).deliver_later
update(unfeasible_email_sent_at: Time.current)
end
def reason_for_not_being_selectable_by(user)
return permission_problem(user) if permission_problem?(user)
return :different_heading_assigned unless valid_heading?(user)
return :no_selecting_allowed unless budget.selecting?
end
def reason_for_not_being_ballotable_by(user, ballot)
return permission_problem(user) if permission_problem?(user)
return :not_selected unless selected?
return :no_ballots_allowed unless budget.balloting?
return :different_heading_assigned unless ballot.valid_heading?(heading)
return :not_enough_money_html if ballot.present? && !enough_money?(ballot)
end
def permission_problem(user)
return :not_logged_in unless user
return :organization if user.organization?
return :not_verified unless user.can?(:vote, Budget::Investment)
nil
end
def permission_problem?(user)
permission_problem(user).present?
end
def selectable_by?(user)
reason_for_not_being_selectable_by(user).blank?
end
def valid_heading?(user)
!different_heading_assigned?(user)
end
def different_heading_assigned?(user)
other_heading_ids = group.heading_ids - [heading.id]
voted_in?(other_heading_ids, user)
end
def voted_in?(heading_ids, user)
heading_ids.include? heading_voted_by_user?(user)
end
def heading_voted_by_user?(user)
user.votes.for_budget_investments(budget.investments.where(group: group))
.votables.map(&:heading_id).first
end
def ballotable_by?(user)
reason_for_not_being_ballotable_by(user).blank?
end
def enough_money?(ballot)
available_money = ballot.amount_available(heading)
price.to_i <= available_money
end
def register_selection(user)
vote_by(voter: user, vote: 'yes') if selectable_by?(user)
end
def calculate_confidence_score
self.confidence_score = ScoreCalculator.confidence_score(total_votes, total_votes)
end
def recalculate_heading_winners
Budget::Result.new(budget, heading).calculate_winners if incompatible_changed?
end
def set_responsible_name
self.responsible_name = author.try(:document_number) if author.try(:document_number).present?
end
def should_show_aside?
(budget.selecting? && !unfeasible?) ||
(budget.balloting? && feasible?) ||
(budget.valuating? && !unfeasible?)
end
def should_show_votes?
budget.selecting?
end
def should_show_vote_count?
budget.valuating?
end
def should_show_ballots?
budget.balloting? && selected?
end
def should_show_price?
selected? && price.present? && budget.published_prices?
end
def should_show_price_explanation?
should_show_price? && price_explanation.present?
end
def formatted_price
budget.formatted_amount(price)
end
def self.apply_filters_and_search(_budget, params, current_filter = nil)
investments = all
investments = investments.send(current_filter) if current_filter.present?
investments = investments.by_heading(params[:heading_id]) if params[:heading_id].present?
investments = investments.search(params[:search]) if params[:search].present?
investments = investments.filter(params[:advanced_search]) if params[:advanced_search].present?
investments
end
def self.to_csv(investments, options = {})
attrs = [I18n.t("admin.budget_investments.index.table_id"),
I18n.t("admin.budget_investments.index.table_title"),
I18n.t("admin.budget_investments.index.table_supports"),
I18n.t("admin.budget_investments.index.table_admin"),
I18n.t("admin.budget_investments.index.table_valuator"),
I18n.t("admin.budget_investments.index.table_geozone"),
I18n.t("admin.budget_investments.index.table_feasibility"),
I18n.t("admin.budget_investments.index.table_valuation_finished"),
I18n.t("admin.budget_investments.index.table_selection")]
csv_string = CSV.generate(options) do |csv|
csv << attrs
investments.each do |investment|
id = investment.id.to_s
title = investment.title
total_votes = investment.total_votes.to_s
admin = if investment.administrator.present?
investment.administrator.name
else
I18n.t("admin.budget_investments.index.no_admin_assigned")
end
vals = if investment.valuators.empty?
I18n.t("admin.budget_investments.index.no_valuators_assigned")
else
investment.valuators.collect(&:description_or_name).join(', ')
end
heading_name = investment.heading.name
price_string = "admin.budget_investments.index.feasibility"\
".#{investment.feasibility}"
price = I18n.t(price_string, price: investment.formatted_price)
valuation_finished = investment.valuation_finished? ?
I18n.t('shared.yes') :
I18n.t('shared.no')
csv << [id, title, total_votes, admin, vals, heading_name, price,
valuation_finished]
end
end
csv_string
end
private
def set_denormalized_ids
self.group_id = heading.try(:group_id) if heading_id_changed?
self.budget_id ||= heading.try(:group).try(:budget_id)
end
end
end
|
class CandidateControl < ActiveRecordShared
belongs_to :study_subject
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :dob
validates_inclusion_of :reject_candidate, :in => [true, false]
validates_presence_of :rejection_reason, :if => :reject_candidate
validates_length_of :related_patid, :is => 4, :allow_blank => true
validates_length_of :state_registrar_no, :maximum => 25, :allow_blank => true
validates_length_of :local_registrar_no, :maximum => 25, :allow_blank => true
validates_length_of :first_name, :middle_name, :last_name,
:birth_county, :birth_type, :mother_maiden_name,
:rejection_reason, :maximum => 250, :allow_blank => true
# validates_inclusion_of :sex, :in => %w( M F DK )
validates_inclusion_of :sex, :in => valid_sex_values
# validates_inclusion_of :mother_hispanicity_id,
# :father_hispanicity_id,
# :in => valid_ynodk_values, :allow_nil => true
# Returns string containing candidates's first, middle and last name
def full_name
[first_name, middle_name, last_name].delete_if(&:blank?).join(' ')
end
# Returns string containing candidates's mother's first, middle and last name
def mother_full_name
[mother_first_name, mother_middle_name, mother_last_name].delete_if(&:blank?).join(' ')
end
def create_study_subjects(case_subject,grouping = '6')
next_orderno = case_subject.next_control_orderno(grouping)
CandidateControl.transaction do
# Use a block so can assign all attributes without concern for attr_protected
child = StudySubject.new do |s|
s.subject_type = SubjectType['Control']
s.vital_status = VitalStatus['living']
s.sex = sex
s.mom_is_biomom = mom_is_biomom
s.dad_is_biodad = dad_is_biodad
s.mother_hispanicity_id = mother_hispanicity_id
s.father_hispanicity_id = father_hispanicity_id
s.birth_type = birth_type
s.mother_yrs_educ = mother_yrs_educ
s.father_yrs_educ = father_yrs_educ
s.birth_county = birth_county
s.hispanicity_id = (
( [mother_hispanicity_id,father_hispanicity_id].include?(1) ) ? 1 : nil )
s.first_name = first_name
s.middle_name = middle_name
s.last_name = last_name
s.dob = dob
s.mother_first_name = mother_first_name
s.mother_middle_name = mother_middle_name
s.mother_last_name = mother_last_name
s.mother_maiden_name = mother_maiden_name
s.mother_race_id = mother_race_id
s.father_race_id = father_race_id
s.case_control_type = grouping
s.state_registrar_no = state_registrar_no
s.local_registrar_no = local_registrar_no
s.orderno = next_orderno
s.matchingid = case_subject.subjectid
s.patid = case_subject.patid
end
child.save!
child.assign_icf_master_id
# NOTE this may require passing info
# that is in the candidate_control record, but not in the child subject
# mother_hispanicity_id
child.create_mother # ({ .... })
self.study_subject_id = child.id
self.assigned_on = Date.today
self.save!
end
self
end
end
Added a couple comments.
class CandidateControl < ActiveRecordShared
belongs_to :study_subject
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :dob
validates_inclusion_of :reject_candidate, :in => [true, false]
validates_presence_of :rejection_reason, :if => :reject_candidate
validates_length_of :related_patid, :is => 4, :allow_blank => true
validates_length_of :state_registrar_no, :maximum => 25, :allow_blank => true
validates_length_of :local_registrar_no, :maximum => 25, :allow_blank => true
validates_length_of :first_name, :middle_name, :last_name,
:birth_county, :birth_type, :mother_maiden_name,
:rejection_reason, :maximum => 250, :allow_blank => true
# validates_inclusion_of :sex, :in => %w( M F DK )
validates_inclusion_of :sex, :in => valid_sex_values
# validates_inclusion_of :mother_hispanicity_id,
# :father_hispanicity_id,
# :in => valid_ynodk_values, :allow_nil => true
# Returns string containing candidates's first, middle and last name
def full_name
[first_name, middle_name, last_name].delete_if(&:blank?).join(' ')
end
# Returns string containing candidates's mother's first, middle and last name
def mother_full_name
[mother_first_name, mother_middle_name, mother_last_name].delete_if(&:blank?).join(' ')
end
def create_study_subjects(case_subject,grouping = '6')
next_orderno = case_subject.next_control_orderno(grouping)
CandidateControl.transaction do
# Use a block so can assign all attributes without concern for attr_protected
child = StudySubject.new do |s|
s.subject_type = SubjectType['Control']
s.vital_status = VitalStatus['living']
s.sex = sex
s.mom_is_biomom = mom_is_biomom
s.dad_is_biodad = dad_is_biodad
s.mother_hispanicity_id = mother_hispanicity_id
s.father_hispanicity_id = father_hispanicity_id
s.birth_type = birth_type
s.mother_yrs_educ = mother_yrs_educ
s.father_yrs_educ = father_yrs_educ
s.birth_county = birth_county
s.hispanicity_id = (
( [mother_hispanicity_id,father_hispanicity_id].include?(1) ) ? 1 : nil )
s.first_name = first_name
s.middle_name = middle_name
s.last_name = last_name
s.dob = dob
s.mother_first_name = mother_first_name
s.mother_middle_name = mother_middle_name
s.mother_last_name = mother_last_name
s.mother_maiden_name = mother_maiden_name
s.mother_race_id = mother_race_id
s.father_race_id = father_race_id
s.case_control_type = grouping
s.state_registrar_no = state_registrar_no
s.local_registrar_no = local_registrar_no
s.orderno = next_orderno
s.matchingid = case_subject.subjectid
s.patid = case_subject.patid
end
child.save!
child.assign_icf_master_id
# TODO May have to set is_matched for both the Case and Control here [#217]
# NOTE this may require passing info
# that is in the candidate_control record, but not in the child subject
# mother_hispanicity_id (actually this is now)
# worst case scenario is just create the full mother here
# rather than through the child.
child.create_mother # ({ .... })
self.study_subject_id = child.id
self.assigned_on = Date.today
self.save!
end
self
end
end
|
module CloudModel
class Guest
require 'resolv'
require 'securerandom'
include Mongoid::Document
include Mongoid::Timestamps
include CloudModel::AcceptSizeStrings
include CloudModel::ENumFields
belongs_to :host, class_name: "CloudModel::Host"
embeds_many :services, class_name: "CloudModel::Services::Base"
has_one :root_volume, class_name: "CloudModel::LogicalVolume", inverse_of: :guest, autobuild: true
accepts_nested_attributes_for :root_volume
has_many :guest_volumes, class_name: "CloudModel::GuestVolume"
accepts_nested_attributes_for :guest_volumes, allow_destroy: true
field :name, type: String
field :private_address, type: String
field :external_address, type: String
field :memory_size, type: Integer, default: 2147483648
field :cpu_count, type: Integer, default: 2
enum_field :deploy_state, values: {
0x00 => :pending,
0x01 => :running,
0xf0 => :finished,
0xf1 => :failed,
0xff => :not_started
}, default: :not_started
field :deploy_last_issue, type: String
attr_accessor :deploy_path, :deploy_volume
def deploy_volume
@deploy_volume ||= root_volume
end
def deploy_path
@deploy_path ||= base_path
end
accept_size_strings_for :memory_size
validates :name, presence: true, uniqueness: { scope: :host }, format: {with: /\A[a-z0-9\-_]+\z/}
validates :host, presence: true
validates :root_volume, presence: true
validates :private_address, presence: true
before_validation :set_dhcp_private_address, :on => :create
before_validation :set_root_volume_name
#after_save :deploy
VM_STATES = {
-1 => :undefined,
0 => :no_state,
1 => :running,
2 => :blocked,
3 => :paused,
4 => :shutdown,
5 => :shutoff,
6 => :crashed,
7 => :suspended
}
def state_to_id state
CloudModel::Livestatus::STATES.invert[state.to_sym] || -1
end
def vm_state_to_id state
VM_STATES.invert[state.to_sym] || -1
end
def base_path
"/vm/#{name}"
end
def config_root_path
"#{base_path}/etc"
end
def available_private_address_collection
([private_address] + host.available_private_address_collection - [nil])
end
def available_external_address_collection
([external_address] + host.available_external_address_collection - [nil])
end
def external_hostname
@external_hostname ||= external_address.blank? ? '' : CloudModel::Address.from_str(external_address).hostname
end
def uuid
SecureRandom.uuid
end
def random_2_digit_hex
"%02x" % SecureRandom.random_number(256)
end
def mac_address
"52:54:00:#{random_2_digit_hex}:#{random_2_digit_hex}:#{random_2_digit_hex}"
end
def to_param
name
end
def exec command
host.exec "LANG=en.UTF-8 /usr/bin/virsh lxc-enter-namespace --noseclabel #{name.shellescape} -- #{command}"
end
def exec! command, message
host.exec! "LANG=en.UTF-8 /usr/bin/virsh lxc-enter-namespace --noseclabel #{name.shellescape} -- #{command}", message
end
def ls directory
res = exec("/bin/ls -l #{directory.shellescape}")
pp res
if res[0]
res[1].split("\n")
else
puts res[1]
false
end
end
def virsh cmd, options = []
option_string = ''
options = [options] if options.is_a? String
options.each do |option|
option_string = "#{option_string}--#{option.shellescape} "
end
success, data = host.exec("LANG=en.UTF-8 /usr/bin/virsh #{cmd.shellescape} #{option_string}#{name.shellescape}")
if success
return data
else
return false
end
end
def has_service?(service_type)
services.select{|s| s._type == service_type}.count > 0
end
def components_needed
components = []
services.each do |service|
components += service.components_needed
end
components.uniq.sort{|a,b| a<=>b}
end
def template_type
CloudModel::GuestTemplateType.find_or_create_by components: components_needed
end
def template
template_type.last_useable(host)
end
def shinken_services_append
services_string = ''
services.each do |service|
if service_string = service.shinken_services_append
services_string += service_string
end
end
services_string
end
def self.deploy_state_id_for deploy_state
enum_fields[:deploy_state][:values].invert[deploy_state]
end
def self.deployable_deploy_states
[:finished, :failed, :not_started]
end
def self.deployable_deploy_state_ids
deployable_deploy_states.map{|s| deploy_state_id_for s}
end
def deployable?
self.class.deployable_deploy_states.include? deploy_state
end
def self.deployable?
where :deploy_state_id.in => deployable_deploy_state_ids
end
def deploy(options = {})
unless deployable? or options[:force]
return false
end
update_attribute :deploy_state, :pending
begin
CloudModel::call_rake 'cloudmodel:guest:deploy', host_id: host_id, guest_id: id
rescue Exception => e
update_attributes deploy_state: :failed, deploy_last_issue: 'Unable to enqueue job! Try again later.'
CloudModel.log_exception e
end
end
def redeploy(options = {})
unless deployable? or options[:force]
return false
end
update_attribute :deploy_state, :pending
begin
CloudModel::call_rake 'cloudmodel:guest:redeploy', host_id: host_id, guest_id: id
rescue Exception => e
update_attributes deploy_state: :failed, deploy_last_issue: 'Unable to enqueue job! Try again later.'
CloudModel.log_exception e
end
end
def redeploy!(options={})
guest_worker = CloudModel::GuestWorker.new self
guest_worker.redeploy options
end
def self.redeploy(ids, options = {})
criteria = self.where(:id.in => ids.map(&:to_s))
valid_ids = criteria.pluck(:_id).map(&:to_s)
return false if valid_ids.empty? and not options[:force]
criteria.update_all deploy_state_id: deploy_state_id_for(:pending)
begin
CloudModel::call_rake 'cloudmodel:guest:redeploy_many', guest_ids: valid_ids * ' '
rescue Exception => e
criteria.update_all deploy_state_id: deploy_state_id_for(:failed), deploy_last_issue: 'Unable to enqueue job! Try again later.'
CloudModel.log_exception e
end
end
def livestatus
@livestatus ||= CloudModel::Livestatus::Host.find("#{host.name}.#{name}", only: %w(host_name description state plugin_output perf_data))
end
def state
if livestatus
livestatus.state
else
-1
end
end
def vm_state
@real_state unless @real_state.blank?
begin
@real_state = vm_state_to_id virsh('domstate').strip
rescue
-1
end
end
def vm_info
@real_vm_info unless @real_vm_info.blank?
begin
vm_info={}
res = virsh('dominfo')
res.lines.each do |line|
k,v = line.split(':')
vm_info[k.gsub(' ', '_').underscore] = v.try(:strip)
end
vm_info['memory'] = vm_info.delete('used_memory').to_i * 1024
vm_info['max_mem'] = vm_info.delete('max_memory').to_i * 1024
vm_info['state'] = vm_state_to_id(vm_info['state'])
vm_info['cpus'] = vm_info.delete("cpu(s)").to_i
vm_info['active'] = (vm_info['state'] == 1)
vm_info
rescue
{"state" => -1}
end
end
def start
begin
return virsh('autostart') && virsh('start')
rescue
return false
end
end
def stop
begin
return virsh('shutdown') && virsh('autostart', 'disable')
rescue
return false
end
end
def stop! options = {}
stop
timeout = options[:timeout] || 600
while vm_state != -1 and timeout > 0 do
sleep 0.1
timeout -= 1
end
end
def undefine
begin
# Return true if the domain is not defined before
if VM_STATES[vm_state] == :undefined
Rails.logger.debug "Domain #{self.name} was not defined before"
return true
end
# If not started shutdown will fail, but if it fails the undefine will fail anyway
stop!
return virsh('undefine')
rescue
return false
end
end
def backup
success = true
guest_volumes.where(has_backups: true).each do |volume|
Rails.logger.debug "V #{volume.mount_point}: #{success &&= volume.backup}"
end
services.where(has_backups: true).each do |service|
Rails.logger.debug "S #{service._type}: #{success &&= service.backup}"
end
success
end
private
def set_dhcp_private_address
self.private_address = host.dhcp_private_address unless private_address
end
def set_root_volume_name
root_volume.name = "#{name}-root-#{Time.now.strftime "%Y%m%d%H%M%S"}" unless root_volume.name
root_volume.volume_group = host.volume_groups.first unless root_volume.volume_group
end
end
end
Ensure guest is undefined before destroy
module CloudModel
class Guest
require 'resolv'
require 'securerandom'
include Mongoid::Document
include Mongoid::Timestamps
include CloudModel::AcceptSizeStrings
include CloudModel::ENumFields
belongs_to :host, class_name: "CloudModel::Host"
embeds_many :services, class_name: "CloudModel::Services::Base"
has_one :root_volume, class_name: "CloudModel::LogicalVolume", inverse_of: :guest, autobuild: true
accepts_nested_attributes_for :root_volume
has_many :guest_volumes, class_name: "CloudModel::GuestVolume"
accepts_nested_attributes_for :guest_volumes, allow_destroy: true
field :name, type: String
field :private_address, type: String
field :external_address, type: String
field :memory_size, type: Integer, default: 2147483648
field :cpu_count, type: Integer, default: 2
enum_field :deploy_state, values: {
0x00 => :pending,
0x01 => :running,
0xf0 => :finished,
0xf1 => :failed,
0xff => :not_started
}, default: :not_started
field :deploy_last_issue, type: String
attr_accessor :deploy_path, :deploy_volume
def deploy_volume
@deploy_volume ||= root_volume
end
def deploy_path
@deploy_path ||= base_path
end
accept_size_strings_for :memory_size
validates :name, presence: true, uniqueness: { scope: :host }, format: {with: /\A[a-z0-9\-_]+\z/}
validates :host, presence: true
validates :root_volume, presence: true
validates :private_address, presence: true
before_validation :set_dhcp_private_address, :on => :create
before_validation :set_root_volume_name
before_destroy :undefine
VM_STATES = {
-1 => :undefined,
0 => :no_state,
1 => :running,
2 => :blocked,
3 => :paused,
4 => :shutdown,
5 => :shutoff,
6 => :crashed,
7 => :suspended
}
def state_to_id state
CloudModel::Livestatus::STATES.invert[state.to_sym] || -1
end
def vm_state_to_id state
VM_STATES.invert[state.to_sym] || -1
end
def base_path
"/vm/#{name}"
end
def config_root_path
"#{base_path}/etc"
end
def available_private_address_collection
([private_address] + host.available_private_address_collection - [nil])
end
def available_external_address_collection
([external_address] + host.available_external_address_collection - [nil])
end
def external_hostname
@external_hostname ||= external_address.blank? ? '' : CloudModel::Address.from_str(external_address).hostname
end
def uuid
SecureRandom.uuid
end
def random_2_digit_hex
"%02x" % SecureRandom.random_number(256)
end
def mac_address
"52:54:00:#{random_2_digit_hex}:#{random_2_digit_hex}:#{random_2_digit_hex}"
end
def to_param
name
end
def exec command
host.exec "LANG=en.UTF-8 /usr/bin/virsh lxc-enter-namespace --noseclabel #{name.shellescape} -- #{command}"
end
def exec! command, message
host.exec! "LANG=en.UTF-8 /usr/bin/virsh lxc-enter-namespace --noseclabel #{name.shellescape} -- #{command}", message
end
def ls directory
res = exec("/bin/ls -l #{directory.shellescape}")
pp res
if res[0]
res[1].split("\n")
else
puts res[1]
false
end
end
def virsh cmd, options = []
option_string = ''
options = [options] if options.is_a? String
options.each do |option|
option_string = "#{option_string}--#{option.shellescape} "
end
success, data = host.exec("LANG=en.UTF-8 /usr/bin/virsh #{cmd.shellescape} #{option_string}#{name.shellescape}")
if success
return data
else
return false
end
end
def has_service?(service_type)
services.select{|s| s._type == service_type}.count > 0
end
def components_needed
components = []
services.each do |service|
components += service.components_needed
end
components.uniq.sort{|a,b| a<=>b}
end
def template_type
CloudModel::GuestTemplateType.find_or_create_by components: components_needed
end
def template
template_type.last_useable(host)
end
def shinken_services_append
services_string = ''
services.each do |service|
if service_string = service.shinken_services_append
services_string += service_string
end
end
services_string
end
def self.deploy_state_id_for deploy_state
enum_fields[:deploy_state][:values].invert[deploy_state]
end
def self.deployable_deploy_states
[:finished, :failed, :not_started]
end
def self.deployable_deploy_state_ids
deployable_deploy_states.map{|s| deploy_state_id_for s}
end
def deployable?
self.class.deployable_deploy_states.include? deploy_state
end
def self.deployable?
where :deploy_state_id.in => deployable_deploy_state_ids
end
def deploy(options = {})
unless deployable? or options[:force]
return false
end
update_attribute :deploy_state, :pending
begin
CloudModel::call_rake 'cloudmodel:guest:deploy', host_id: host_id, guest_id: id
rescue Exception => e
update_attributes deploy_state: :failed, deploy_last_issue: 'Unable to enqueue job! Try again later.'
CloudModel.log_exception e
end
end
def redeploy(options = {})
unless deployable? or options[:force]
return false
end
update_attribute :deploy_state, :pending
begin
CloudModel::call_rake 'cloudmodel:guest:redeploy', host_id: host_id, guest_id: id
rescue Exception => e
update_attributes deploy_state: :failed, deploy_last_issue: 'Unable to enqueue job! Try again later.'
CloudModel.log_exception e
end
end
def redeploy!(options={})
guest_worker = CloudModel::GuestWorker.new self
guest_worker.redeploy options
end
def self.redeploy(ids, options = {})
criteria = self.where(:id.in => ids.map(&:to_s))
valid_ids = criteria.pluck(:_id).map(&:to_s)
return false if valid_ids.empty? and not options[:force]
criteria.update_all deploy_state_id: deploy_state_id_for(:pending)
begin
CloudModel::call_rake 'cloudmodel:guest:redeploy_many', guest_ids: valid_ids * ' '
rescue Exception => e
criteria.update_all deploy_state_id: deploy_state_id_for(:failed), deploy_last_issue: 'Unable to enqueue job! Try again later.'
CloudModel.log_exception e
end
end
def livestatus
@livestatus ||= CloudModel::Livestatus::Host.find("#{host.name}.#{name}", only: %w(host_name description state plugin_output perf_data))
end
def state
if livestatus
livestatus.state
else
-1
end
end
def vm_state
@real_state unless @real_state.blank?
begin
@real_state = vm_state_to_id virsh('domstate').strip
rescue
-1
end
end
def vm_info
@real_vm_info unless @real_vm_info.blank?
begin
vm_info={}
res = virsh('dominfo')
res.lines.each do |line|
k,v = line.split(':')
vm_info[k.gsub(' ', '_').underscore] = v.try(:strip)
end
vm_info['memory'] = vm_info.delete('used_memory').to_i * 1024
vm_info['max_mem'] = vm_info.delete('max_memory').to_i * 1024
vm_info['state'] = vm_state_to_id(vm_info['state'])
vm_info['cpus'] = vm_info.delete("cpu(s)").to_i
vm_info['active'] = (vm_info['state'] == 1)
vm_info
rescue
{"state" => -1}
end
end
def start
begin
return virsh('autostart') && virsh('start')
rescue
return false
end
end
def stop
begin
return virsh('shutdown') && virsh('autostart', 'disable')
rescue
return false
end
end
def stop! options = {}
stop
timeout = options[:timeout] || 600
while vm_state != -1 and timeout > 0 do
sleep 0.1
timeout -= 1
end
end
def undefine
begin
# Return true if the domain is not defined before
if VM_STATES[vm_state] == :undefined
Rails.logger.debug "Domain #{self.name} was not defined before"
return true
end
# If not started shutdown will fail, but if it fails the undefine will fail anyway
stop!
return virsh('undefine')
rescue
return false
end
end
def backup
success = true
guest_volumes.where(has_backups: true).each do |volume|
Rails.logger.debug "V #{volume.mount_point}: #{success &&= volume.backup}"
end
services.where(has_backups: true).each do |service|
Rails.logger.debug "S #{service._type}: #{success &&= service.backup}"
end
success
end
private
def set_dhcp_private_address
self.private_address = host.dhcp_private_address unless private_address
end
def set_root_volume_name
root_volume.name = "#{name}-root-#{Time.now.strftime "%Y%m%d%H%M%S"}" unless root_volume.name
root_volume.volume_group = host.volume_groups.first unless root_volume.volume_group
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.