text
stringlengths
10
2.61M
require File.dirname(__FILE__) + '/spec_helper' def get_month(val) months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] months[val - 1] end def get_options(from_val,to_val, hash = {}) options = "" range = (from_val..to_val) if hash[:reverse] range = range.to_a.reverse end range.each do |val| if hash[:label_func] print_val = send(hash[:label_func], val) else print_val = fill_zeros(val) end options << %{<option value="#{val}">#{print_val}</option>} end options end def fill_zeros(val) if val < 10 "0#{val}" else val end end describe "tags for forms that use models" do include Clot::UrlFilters include Clot::FormFilters include Liquid def parse_form_tag_to(inner_code, hash = {}) template = "{% formfor dummy %}#{@tag}{% endformfor %}" expected = %{<form method="POST" action="#{object_url @user}"><input type="hidden" name="_method" value="PUT"/>#{inner_code}</form>} template.should parse_with_vars_to(expected, hash.merge( 'dummy' => @user)) end def tag_should_parse_to(expected, hash = {}) @tag.should parse_with_vars_to(expected, hash.merge( 'dummy' => @user )) end before do @time = Time.now @user = mock_drop user_default_values @user.stub!(:registered_at).and_return(@time) end context "for datetime_select" do context "within form" do it "should generate selection event when class is nil" do @user.stub!(:registered_at).and_return(nil) @tag = "{% datetime_select 'registered_at' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]">' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]">' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" parse_form_tag_to @year_string + @month_string + @day_string + @hour_string + @minute_string end end it "should generate selection" do @tag = "{% datetime_select dummy,'registered_at' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]">' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]">' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end it "should take separators" do @tag = "{% datetime_select dummy,'registered_at',date_separator:'/',datetime_separator:' - ',time_separator:':' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]">' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]">' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + '/' + @month_string + '/' + @day_string + ' - ' + @hour_string + ':' + @minute_string end it "should take prompts" do @tag = "{% datetime_select dummy,'registered_at',year_prompt:true,month_prompt:'pick a month',hour_prompt:'hora' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]"><option value="">Years</option>' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]"><option value="">pick a month</option>' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]"><option value="">hora</option>' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]">' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end it "should take default prompts" do @tag = "{% datetime_select dummy,'registered_at',prompt:true %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]"><option value="">Years</option>' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]"><option value="">Months</option>' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]"><option value="">Days</option>' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]"><option value="">Hours</option>' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]"><option value="">Minutes</option>' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end end context "for date_select" do context "within form" do it "should generate selection event when class is nil" do @user.stub!(:registered_at).and_return(nil) @tag = "{% date_select 'registered_at' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" parse_form_tag_to @year_string + @month_string + @day_string end end it "should generate selection based on model and field" do @tag = "{% date_select dummy,'registered_at' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string end it "should take prompts" do @tag = "{% date_select dummy,'registered_at',day_prompt:'Choose Day',month_prompt:'Choose Month',year_prompt:'Choose Year' %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]"><option value="">Choose Year</option>' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]"><option value="">Choose Month</option>' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]"><option value="">Choose Day</option>' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string end it "should generate selection with start year" do @tag = "{% date_select dummy,'registered_at',start_year:1995 %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(1995,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string end it "should generate selection with start year, month_numbers, blank, and excluding day" do @tag = "{% date_select dummy,'registered_at',start_year:1995,use_month_numbers:true,discard_day:true,include_blank:true %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]"><option value=""></option>' + get_options(1995,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]"><option value=""></option>' + get_options(1,@time.month - 1) + %{<option selected="selected" value="#{@time.month}">#{fill_zeros @time.month}</option>} + get_options(@time.month + 1,12) + "</select>" tag_should_parse_to @year_string + @month_string end it "should allow reordering" do @tag = "{% date_select dummy,'registered_at',order:['month' 'day' 'year'] %}" @year_string = '<select id="dummy_registered_at_1i" name="dummy[registered_at(1i)]">' + get_options(@time.year-5,@time.year - 1) + %{<option selected="selected" value="#{@time.year}">#{@time.year}</option>} + get_options(@time.year + 1,@time.year + 5) + "</select>" @month_string = '<select id="dummy_registered_at_2i" name="dummy[registered_at(2i)]">' + get_options(1,@time.month - 1,{:label_func => :get_month}) + %{<option selected="selected" value="#{@time.month}">#{get_month @time.month}</option>} + get_options(@time.month + 1,12,{:label_func => :get_month}) + "</select>" @day_string = '<select id="dummy_registered_at_3i" name="dummy[registered_at(3i)]">' + get_options(1,(@time.day - 1)) + %{<option selected="selected" value="#{@time.day}">#{fill_zeros @time.day}</option>} + get_options((@time.day + 1),31) + "</select>" tag_should_parse_to @month_string + @day_string + @year_string end end context "for time_select" do context "within form" do it "should generate selection event when class is nil" do @user.stub!(:registered_at).and_return(nil) @tag = "{% time_select 'registered_at' %}" @year_string = %{<input id="dummy_registered_at_1i" name="dummy[registered_at(1i)]" type="hidden" value="#{@time.year}" />} @month_string = %{<input id="dummy_registered_at_2i" name="dummy[registered_at(2i)]" type="hidden" value="#{@time.month}" />} @day_string = %{<input id="dummy_registered_at_3i" name="dummy[registered_at(3i)]" type="hidden" value="#{@time.day}" />} @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]">' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]">' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" parse_form_tag_to @year_string + @month_string + @day_string + @hour_string + @minute_string end end it "should generate selection based on model and field" do @tag = "{% time_select dummy,'registered_at' %}" @year_string = %{<input id="dummy_registered_at_1i" name="dummy[registered_at(1i)]" type="hidden" value="#{@time.year}" />} @month_string = %{<input id="dummy_registered_at_2i" name="dummy[registered_at(2i)]" type="hidden" value="#{@time.month}" />} @day_string = %{<input id="dummy_registered_at_3i" name="dummy[registered_at(3i)]" type="hidden" value="#{@time.day}" />} @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]">' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]">' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end it "should allow prompt to be included" do @tag = "{% time_select dummy,'registered_at',hour_prompt:'choose hour',minute_prompt:'choose minute' %}" @year_string = %{<input id="dummy_registered_at_1i" name="dummy[registered_at(1i)]" type="hidden" value="#{@time.year}" />} @month_string = %{<input id="dummy_registered_at_2i" name="dummy[registered_at(2i)]" type="hidden" value="#{@time.month}" />} @day_string = %{<input id="dummy_registered_at_3i" name="dummy[registered_at(3i)]" type="hidden" value="#{@time.day}" />} @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]"><option value="">choose hour</option>' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]"><option value="">choose minute</option>' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end it "should allow default prompts to be included" do @tag = "{% time_select dummy,'registered_at',hour_prompt:true,minute_prompt:true %}" @year_string = %{<input id="dummy_registered_at_1i" name="dummy[registered_at(1i)]" type="hidden" value="#{@time.year}" />} @month_string = %{<input id="dummy_registered_at_2i" name="dummy[registered_at(2i)]" type="hidden" value="#{@time.month}" />} @day_string = %{<input id="dummy_registered_at_3i" name="dummy[registered_at(3i)]" type="hidden" value="#{@time.day}" />} @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]"><option value="">Hours</option>' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]"><option value="">Minutes</option>' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end it "should allow default prompt to be included" do @tag = "{% time_select dummy,'registered_at',prompt:true %}" @year_string = %{<input id="dummy_registered_at_1i" name="dummy[registered_at(1i)]" type="hidden" value="#{@time.year}" />} @month_string = %{<input id="dummy_registered_at_2i" name="dummy[registered_at(2i)]" type="hidden" value="#{@time.month}" />} @day_string = %{<input id="dummy_registered_at_3i" name="dummy[registered_at(3i)]" type="hidden" value="#{@time.day}" />} @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]"><option value="">Hours</option>' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros @time.hour}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]"><option value="">Minutes</option>' + get_options(0,(@time.min - 1)) + %{<option selected="selected" value="#{@time.min}">#{fill_zeros @time.min}</option>} + get_options((@time.min + 1),59) + "</select>" tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end it "should allow minute steps to be included" do @tag = "{% time_select dummy,'registered_at',minute_step:15 %}" @time.stub!(:min).and_return(15) @year_string = %{<input id="dummy_registered_at_1i" name="dummy[registered_at(1i)]" type="hidden" value="#{@time.year}" />} @month_string = %{<input id="dummy_registered_at_2i" name="dummy[registered_at(2i)]" type="hidden" value="#{@time.month}" />} @day_string = %{<input id="dummy_registered_at_3i" name="dummy[registered_at(3i)]" type="hidden" value="#{@time.day}" />} @hour_string = '<select id="dummy_registered_at_4i" name="dummy[registered_at(4i)]">' + get_options(0,(@time.hour - 1)) + %{<option selected="selected" value="#{@time.hour}">#{fill_zeros(@time.hour)}</option>} + get_options((@time.hour + 1),59) + "</select>" @minute_string = '<select id="dummy_registered_at_5i" name="dummy[registered_at(5i)]"><option value="0">00</option><option selected="selected" value="15">15</option><option value="30">30</option><option value="45">45</option></select>' tag_should_parse_to @year_string + @month_string + @day_string + @hour_string + @minute_string end end end
Rails.application.routes.draw do root 'pages#index' #resources :pages get 'property', to: 'pages#show' get 'property_card', to: 'pages#property_card' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end
module Garrison class AwsHelper def self.whoami @whoami ||= Aws::STS::Client.new(region: 'us-east-1').get_caller_identity.account end def self.all_regions Aws::Partitions.partition('aws').service('SQS').regions end def self.list_sqs_queues(region, attributes) if ENV['AWS_ASSUME_ROLE_CREDENTIALS_ARN'] role_credentials = Aws::AssumeRoleCredentials.new( client: Aws::STS::Client.new(region: region), role_arn: ENV['AWS_ASSUME_ROLE_CREDENTIALS_ARN'], role_session_name: 'garrison-agent-sqs' ) sqs = Aws::SQS::Client.new(credentials: role_credentials, region: region, logger: Logging, log_level: :debug) else sqs = Aws::SQS::Client.new(region: region, logger: Logging, log_level: :debug) end queue_urls = sqs.list_queues["queue_urls"] attrs = ["QueueArn"] + attributes queue_urls.map! do |queue_url| queue = sqs.get_queue_attributes(queue_url: queue_url, attribute_names: attrs).attributes { "QueueUrl" => queue_url }.merge(queue) end rescue Aws::SQS::Errors::OptInRequired => e Logging.warn "#{region} - #{e.message}" return [] rescue Aws::SQS::Errors::InvalidClientTokenId => e Logging.warn "#{region} - #{e.message}" return [] end end end
class AddPlanetIdToReplies < ActiveRecord::Migration[5.2] def change add_column :replies, :planet_id, :integer end end
class Achievement < ActiveRecord::Base belongs_to :user belongs_to :achievement_category belongs_to :achievement_result has_many :groups, through: :user has_and_belongs_to_many :attachments, dependent: :destroy validates :event_name, :achievement_category_id, :achievement_result_id, :event_date, presence: true end
require 'adcenter_wrapper_entities' require 'soap/mapping' module AdCenterWrapper module SecureDataManagementServiceMappingRegistry EncodedRegistry = ::SOAP::Mapping::EncodedRegistry.new LiteralRegistry = ::SOAP::Mapping::LiteralRegistry.new NsAdapiMicrosoftCom = "https://adapi.microsoft.com" NsC_Exception = "https://adcenter.microsoft.com/api/customermanagement/Exception" NsEntities = "https://adcenter.microsoft.com/api/customermanagement/Entities" NsSecuredatamanagement = "https://adcenter.microsoft.com/api/securedatamanagement" EncodedRegistry.register( :class => AdCenterWrapper::PaymentMethod, :schema_type => XSD::QName.new(NsEntities, "PaymentMethod"), :schema_element => [ ["address", ["AdCenterWrapper::Address", XSD::QName.new(NsEntities, "Address")], [0, 1]], ["customerId", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "CustomerId")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::Address, :schema_type => XSD::QName.new(NsEntities, "Address"), :schema_element => [ ["city", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "City")], [0, 1]], ["countryCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "CountryCode")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["line1", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line1")], [0, 1]], ["line2", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line2")], [0, 1]], ["line3", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line3")], [0, 1]], ["line4", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line4")], [0, 1]], ["postalCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "PostalCode")], [0, 1]], ["stateOrProvince", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "StateOrProvince")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::CreditCardPaymentMethod, :schema_type => XSD::QName.new(NsEntities, "CreditCardPaymentMethod"), :schema_basetype => XSD::QName.new(NsEntities, "PaymentMethod"), :schema_element => [ ["address", ["AdCenterWrapper::Address", XSD::QName.new(NsEntities, "Address")], [0, 1]], ["customerId", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "CustomerId")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]], ["expirationDate", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "ExpirationDate")], [0, 1]], ["firstName", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "FirstName")], [0, 1]], ["lastName", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "LastName")], [0, 1]], ["middleInitial", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "MiddleInitial")], [0, 1]], ["number", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Number")], [0, 1]], ["securityCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "SecurityCode")], [0, 1]], ["type", ["AdCenterWrapper::CreditCardType", XSD::QName.new(NsEntities, "Type")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::AdApiFaultDetail, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "AdApiFaultDetail"), :schema_basetype => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]], ["errors", ["AdCenterWrapper::ArrayOfAdApiError", XSD::QName.new(NsAdapiMicrosoftCom, "Errors")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::ApplicationFault, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::ArrayOfAdApiError, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "ArrayOfAdApiError"), :schema_element => [ ["adApiError", ["AdCenterWrapper::AdApiError[]", XSD::QName.new(NsAdapiMicrosoftCom, "AdApiError")], [0, nil]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::AdApiError, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "AdApiError"), :schema_element => [ ["code", ["SOAP::SOAPInt", XSD::QName.new(NsAdapiMicrosoftCom, "Code")], [0, 1]], ["detail", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "Detail")], [0, 1]], ["errorCode", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "ErrorCode")], [0, 1]], ["message", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "Message")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::ApiFault, :schema_type => XSD::QName.new(NsC_Exception, "ApiFault"), :schema_basetype => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]], ["operationErrors", ["AdCenterWrapper::ArrayOfOperationError", XSD::QName.new(NsC_Exception, "OperationErrors")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::ArrayOfOperationError, :schema_type => XSD::QName.new(NsC_Exception, "ArrayOfOperationError"), :schema_element => [ ["operationError", ["AdCenterWrapper::OperationError[]", XSD::QName.new(NsC_Exception, "OperationError")], [0, nil]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::OperationError, :schema_type => XSD::QName.new(NsC_Exception, "OperationError"), :schema_element => [ ["code", ["SOAP::SOAPInt", XSD::QName.new(NsC_Exception, "Code")], [0, 1]], ["details", ["SOAP::SOAPString", XSD::QName.new(NsC_Exception, "Details")], [0, 1]], ["message", ["SOAP::SOAPString", XSD::QName.new(NsC_Exception, "Message")], [0, 1]] ] ) EncodedRegistry.register( :class => AdCenterWrapper::CreditCardType, :schema_type => XSD::QName.new(NsEntities, "CreditCardType") ) LiteralRegistry.register( :class => AdCenterWrapper::PaymentMethod, :schema_type => XSD::QName.new(NsEntities, "PaymentMethod"), :schema_element => [ ["address", ["AdCenterWrapper::Address", XSD::QName.new(NsEntities, "Address")], [0, 1]], ["customerId", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "CustomerId")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::Address, :schema_type => XSD::QName.new(NsEntities, "Address"), :schema_element => [ ["city", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "City")], [0, 1]], ["countryCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "CountryCode")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["line1", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line1")], [0, 1]], ["line2", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line2")], [0, 1]], ["line3", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line3")], [0, 1]], ["line4", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line4")], [0, 1]], ["postalCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "PostalCode")], [0, 1]], ["stateOrProvince", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "StateOrProvince")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::CreditCardPaymentMethod, :schema_type => XSD::QName.new(NsEntities, "CreditCardPaymentMethod"), :schema_basetype => XSD::QName.new(NsEntities, "PaymentMethod"), :schema_element => [ ["address", ["AdCenterWrapper::Address", XSD::QName.new(NsEntities, "Address")], [0, 1]], ["customerId", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "CustomerId")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]], ["expirationDate", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "ExpirationDate")], [0, 1]], ["firstName", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "FirstName")], [0, 1]], ["lastName", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "LastName")], [0, 1]], ["middleInitial", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "MiddleInitial")], [0, 1]], ["number", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Number")], [0, 1]], ["securityCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "SecurityCode")], [0, 1]], ["type", ["AdCenterWrapper::CreditCardType", XSD::QName.new(NsEntities, "Type")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::AdApiFaultDetail, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "AdApiFaultDetail"), :schema_basetype => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]], ["errors", ["AdCenterWrapper::ArrayOfAdApiError", XSD::QName.new(NsAdapiMicrosoftCom, "Errors")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ApplicationFault, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ArrayOfAdApiError, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "ArrayOfAdApiError"), :schema_element => [ ["adApiError", ["AdCenterWrapper::AdApiError[]", XSD::QName.new(NsAdapiMicrosoftCom, "AdApiError")], [0, nil]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::AdApiError, :schema_type => XSD::QName.new(NsAdapiMicrosoftCom, "AdApiError"), :schema_element => [ ["code", ["SOAP::SOAPInt", XSD::QName.new(NsAdapiMicrosoftCom, "Code")], [0, 1]], ["detail", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "Detail")], [0, 1]], ["errorCode", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "ErrorCode")], [0, 1]], ["message", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "Message")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ApiFault, :schema_type => XSD::QName.new(NsC_Exception, "ApiFault"), :schema_basetype => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]], ["operationErrors", ["AdCenterWrapper::ArrayOfOperationError", XSD::QName.new(NsC_Exception, "OperationErrors")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ArrayOfOperationError, :schema_type => XSD::QName.new(NsC_Exception, "ArrayOfOperationError"), :schema_element => [ ["operationError", ["AdCenterWrapper::OperationError[]", XSD::QName.new(NsC_Exception, "OperationError")], [0, nil]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::OperationError, :schema_type => XSD::QName.new(NsC_Exception, "OperationError"), :schema_element => [ ["code", ["SOAP::SOAPInt", XSD::QName.new(NsC_Exception, "Code")], [0, 1]], ["details", ["SOAP::SOAPString", XSD::QName.new(NsC_Exception, "Details")], [0, 1]], ["message", ["SOAP::SOAPString", XSD::QName.new(NsC_Exception, "Message")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::CreditCardType, :schema_type => XSD::QName.new(NsEntities, "CreditCardType") ) LiteralRegistry.register( :class => AdCenterWrapper::AddPaymentMethodRequest, :schema_name => XSD::QName.new(NsSecuredatamanagement, "AddPaymentMethodRequest"), :schema_element => [ ["paymentMethod", ["AdCenterWrapper::PaymentMethod", XSD::QName.new(NsSecuredatamanagement, "PaymentMethod")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::AddPaymentMethodResponse, :schema_name => XSD::QName.new(NsSecuredatamanagement, "AddPaymentMethodResponse"), :schema_element => [ ["paymentMethodId", ["SOAP::SOAPLong", XSD::QName.new(NsSecuredatamanagement, "PaymentMethodId")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::PaymentMethod, :schema_name => XSD::QName.new(NsEntities, "PaymentMethod"), :schema_element => [ ["address", ["AdCenterWrapper::Address", XSD::QName.new(NsEntities, "Address")], [0, 1]], ["customerId", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "CustomerId")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::Address, :schema_name => XSD::QName.new(NsEntities, "Address"), :schema_element => [ ["city", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "City")], [0, 1]], ["countryCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "CountryCode")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["line1", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line1")], [0, 1]], ["line2", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line2")], [0, 1]], ["line3", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line3")], [0, 1]], ["line4", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Line4")], [0, 1]], ["postalCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "PostalCode")], [0, 1]], ["stateOrProvince", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "StateOrProvince")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::CreditCardPaymentMethod, :schema_name => XSD::QName.new(NsEntities, "CreditCardPaymentMethod"), :schema_element => [ ["address", ["AdCenterWrapper::Address", XSD::QName.new(NsEntities, "Address")], [0, 1]], ["customerId", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "CustomerId")], [0, 1]], ["id", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "Id")], [0, 1]], ["timeStamp", ["SOAP::SOAPBase64", XSD::QName.new(NsEntities, "TimeStamp")], [0, 1]], ["expirationDate", ["SOAP::SOAPLong", XSD::QName.new(NsEntities, "ExpirationDate")], [0, 1]], ["firstName", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "FirstName")], [0, 1]], ["lastName", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "LastName")], [0, 1]], ["middleInitial", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "MiddleInitial")], [0, 1]], ["number", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "Number")], [0, 1]], ["securityCode", ["SOAP::SOAPString", XSD::QName.new(NsEntities, "SecurityCode")], [0, 1]], ["type", ["AdCenterWrapper::CreditCardType", XSD::QName.new(NsEntities, "Type")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::CreditCardType, :schema_name => XSD::QName.new(NsEntities, "CreditCardType") ) LiteralRegistry.register( :class => AdCenterWrapper::AdApiFaultDetail, :schema_name => XSD::QName.new(NsAdapiMicrosoftCom, "AdApiFaultDetail"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]], ["errors", ["AdCenterWrapper::ArrayOfAdApiError", XSD::QName.new(NsAdapiMicrosoftCom, "Errors")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ApplicationFault, :schema_name => XSD::QName.new(NsAdapiMicrosoftCom, "ApplicationFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ArrayOfAdApiError, :schema_name => XSD::QName.new(NsAdapiMicrosoftCom, "ArrayOfAdApiError"), :schema_element => [ ["adApiError", ["AdCenterWrapper::AdApiError[]", XSD::QName.new(NsAdapiMicrosoftCom, "AdApiError")], [0, nil]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::AdApiError, :schema_name => XSD::QName.new(NsAdapiMicrosoftCom, "AdApiError"), :schema_element => [ ["code", ["SOAP::SOAPInt", XSD::QName.new(NsAdapiMicrosoftCom, "Code")], [0, 1]], ["detail", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "Detail")], [0, 1]], ["errorCode", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "ErrorCode")], [0, 1]], ["message", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "Message")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ApiFault, :schema_name => XSD::QName.new(NsC_Exception, "ApiFault"), :schema_element => [ ["trackingId", ["SOAP::SOAPString", XSD::QName.new(NsAdapiMicrosoftCom, "TrackingId")], [0, 1]], ["operationErrors", ["AdCenterWrapper::ArrayOfOperationError", XSD::QName.new(NsC_Exception, "OperationErrors")], [0, 1]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::ArrayOfOperationError, :schema_name => XSD::QName.new(NsC_Exception, "ArrayOfOperationError"), :schema_element => [ ["operationError", ["AdCenterWrapper::OperationError[]", XSD::QName.new(NsC_Exception, "OperationError")], [0, nil]] ] ) LiteralRegistry.register( :class => AdCenterWrapper::OperationError, :schema_name => XSD::QName.new(NsC_Exception, "OperationError"), :schema_element => [ ["code", ["SOAP::SOAPInt", XSD::QName.new(NsC_Exception, "Code")], [0, 1]], ["details", ["SOAP::SOAPString", XSD::QName.new(NsC_Exception, "Details")], [0, 1]], ["message", ["SOAP::SOAPString", XSD::QName.new(NsC_Exception, "Message")], [0, 1]] ] ) end end
# courtesy of abhishekkr # https://gist.github.com/abhishekkr/3610174#file-term_color-rb # get colored terminal output using these String methods class String def colortxt(txt, term_color_code) "\e[#{term_color_code}m#{txt}\e[0m" end def bold; colortxt(self, 1); end def thin; colortxt(self, 2); end def underline; colortxt(self, 4); end def blink; colortxt(self, 5); end def highlight; colortxt(self, 7); end def hidden; colortxt(self, 8); end def strikethrough; colortxt(self, 9); end def black; colortxt(self, 30); end def red; colortxt(self, 31); end def green; colortxt(self, 32); end def yellow; colortxt(self, 33); end def blue; colortxt(self, 34); end def magenta; colortxt(self, 35); end def cyan; colortxt(self, 36); end def white; colortxt(self, 37); end def default; colortxt(self, 39); end def black_bg; colortxt(self, 40); end def red_bg; colortxt(self, 41); end def green_bg; colortxt(self, 42); end def yellow_bg; colortxt(self, 43); end def blue_bg; colortxt(self, 44); end def magenta_bg; colortxt(self, 45); end def cyan_bg; colortxt(self, 46); end def white_bg; colortxt(self, 47); end def default_bg; colortxt(self, 49); end def grey; colortxt(self, 90); end def bright_red; colortxt(self, 91); end def bright_green; colortxt(self, 92); end def bright_yellow; colortxt(self, 93); end def bright_blue; colortxt(self, 94); end def bright_magenta; colortxt(self, 95); end def bright_cyan; colortxt(self, 96); end def bright_white; colortxt(self, 97); end def grey_bg; colortxt(self, 100); end def bright_red_bg; colortxt(self, 101); end def bright_green_bg; colortxt(self, 102); end def bright_yellow_bg; colortxt(self, 103); end def bright_blue_bg; colortxt(self, 104); end def bright_magent_bg; colortxt(self, 105); end def bright_cyan_bg; colortxt(self, 106); end def bright_white_bg; colortxt(self, 107); end end
# Encoding: utf-8 require_relative '../CartoCSSHelper/lib/cartocss_helper' require_relative '../CartoCSSHelper/lib/cartocss_helper/configuration' require_relative '../CartoCSSHelper/lib/cartocss_helper/visualise_changes_image_generation' require_relative '../CartoCSSHelper/lib/cartocss_helper/util/filehelper' require_relative 'gsoc' require_relative 'archive' require_relative 'road_grid' require_relative 'startup' require_relative 'precartocssshelper' include CartoCSSHelper require 'fileutils' #TODO w renderowaniu miejsc przeskocz nad tymi gdzie miejsce jest znane a plik jest nadal do pobrania - oznacza to iż jest on wileki, został skasowany przy czyszczeniu nadmiaru a będzie się module CartoCSSHelper def main #CartoCSSHelper::test_tag_on_sythetic_data({'barrier' => 'swing_gate'}, 'swing') #CartoCSSHelper::VisualDiff.visualise_changes_synthethic_test({'oneway' => 'yes', 'highway' => 'path'}, 'way', false, 8..22, 'nebulon/oneway-bicycle-designated', 'master') #CartoCSSHelper.test_tag_on_real_data_for_this_type({'tourism' => 'information'}, 'kocio/information-icon', 'master', 14..22, 'node', 5) #CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'bus_station'}, 'kocio/bus_station-icon', 'master', 14..22, 'node', 5) CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'library'}, 'kocio/library-icon-open', 'master', 22..22, 'node', 5, 115) CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'library'}, 'kocio/library-icon-open', 'master', 14..22, 'node', 5) CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'library'}, 'kocio/library-icon-open', 'master', 14..22, 'node', 5) CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'library'}, 'kocio/library-icon-open', 'master', 14..22, 'closed_way', 5) final reload_databases() #create_databases before_after_from_loaded_databases({'amenity' => 'library'}, 'kocio/library-icon', 'master', 15..18, 300, 1) final branch = 'master' CartoCSSHelper.test_tag_on_real_data_for_this_type({'highway' => 'turning_circle'}, branch, 'master', 15..18, 'node', 2) before_after_from_loaded_databases({'highway' => 'turning_circle'}, branch, 'master', 15..18, 300, 1) #test_tag_on_real_data_pair_for_this_type({'highway'=>'turning_circle'}, {'highway' => 'service'}, branch, 'master', 15..18, 'way', 1, 0, 375) #test_tag_on_real_data_pair_for_this_type({'highway'=>'turning_circle'}, {'highway' => 'service', 'service' => 'driveway'}, branch, 'master', 15..18, 'way', 1, 0, 375) #test_tag_on_real_data_pair_for_this_type({'highway'=>'turning_circle'}, {'highway' => 'living_street'}, branch, 'master', 15..18, 'way', 1, 0, 375) #test_tag_on_real_data_pair_for_this_type({'highway'=>'turning_circle'}, {'highway' => 'service', 'service' => 'parking_aisle'}, branch, 'master', 15..18, 'way', 1, 0, 375) #switch_databases('gis_test', 'new_york') #final #generate_preview(['master']) #switch_databases('gis_test', 'krakow') #final #before_after_from_loaded_databases({'leisure' => 'marina'}, 'math/marina-label', 'master', 15..19, 300, 10) #before_after_from_loaded_databases({'amenity' => 'taxi'}, 'math/taxi-zoomlevel', 'master', 15..19, 300, 10) get_all_road_types.each{|highway| puts highway before_after_from_loaded_databases({'highway' => highway, 'ref' => :any_value}, 'nebulon/road-shields', 'master', 13..22, 1000, 5) } #PR puiblished #CartoCSSHelper.visualise_place_by_url('http://www.openstreetmap.org/way/256157138#map=18/50.94165/6.96538', 18..18, 'barrier_way', 'master', 'tourism_way', 0.1) #CartoCSSHelper.visualise_place_by_url('http://www.openstreetmap.org/way/256157138#map=18/50.94165/6.96538', 15..22, 'barrier_way', 'master', 'tourism_way', 0.1) #CartoCSSHelper.probe({'barrier' => 'wall', 'name' => :any_value, 'landuse' => 'cemetery'}, 'barrier_way', 'master', 19..19) #CartoCSSHelper.probe({'barrier' => 'wall', 'name' => :any_value}, 'barrier_way', 'master', 19..19) #CartoCSSHelper.probe({'barrier' => 'wall', 'name' => :any_value}, 'barrier_way', 'master', 8..8) #CartoCSSHelper.probe({'barrier' => 'wall', 'name' => :any_value}, 'barrier_way', 'master') #before_after_from_loaded_databases({'barrier' => 'wall', 'name' => :any_value}, 'barrier_way', 'master', 15..19, 600, 1) #before_after_from_loaded_databases({'barrier' => 'wall', 'name' => :any_value}, 'barrier_way', 'master', 15..19) #before_after_from_loaded_databases({'barrier' => :any_value, 'name' => :any_value}, 'barrier_way', 'master', 15..19) #CartoCSSHelper.test({'barrier' => 'wall', 'name' => :any_value}, 'barrier_way', 'master') =begin ['barrier_way', 'tourism_way'].each{|branch| CartoCSSHelper.probe({'tourism' => 'attraction'}, branch, 'master') CartoCSSHelper.probe({'waterway' => 'dam'}, branch, 'master') CartoCSSHelper.probe({'waterway' => 'weir'}, branch, 'master') CartoCSSHelper.probe({'man_made' => 'pier'}, branch, 'master') CartoCSSHelper.probe({'man_made' => 'breakwater'}, branch, 'master') CartoCSSHelper.probe({'man_made' => 'groyne'}, branch, 'master') CartoCSSHelper.probe({'man_made' => 'embankment'}, branch, 'master') CartoCSSHelper.probe({'natural' => 'cliff'}, branch, 'master') } final =end #CartoCSSHelper.probe({'tourism' => 'attraction'}, 'tourism_way', 'master', 19..19) #CartoCSSHelper.visualise_place_by_url('http://www.openstreetmap.org/way/256157138#map=18/50.94165/6.96538', 18..18, 'tourism_way', 'master', 'tourism_way', 0.1) #CartoCSSHelper.visualise_place_by_url('http://www.openstreetmap.org/way/256157138#map=18/50.94165/6.96538', 13..22, 'tourism_way', 'master', 'tourism_way', 0.1) final #https://github.com/gravitystorm/openstreetmap-carto/issues/1781 - tweaking water colour #TODO - from world database #before_after_from_loaded_databases({'waterway' => 'river'}, 'water', 'master', 9..19, 1000) #before_after_from_loaded_databases({'waterway' => 'stream'}, 'water', 'master', 9..19, 1000) #before_after_from_loaded_databases({'waterway' => 'ditch'}, 'water', 'master', 9..19, 1000) #before_after_from_loaded_databases({'waterway' => 'riverbank'}, 'water', 'master', 9..19, 1000) #before_after_from_loaded_databases({'natural' => 'coastline'}, 'water', 'master', 9..19, 1000) #final #CartoCSSHelper::VisualDiff.visualise_changes_synthethic_test({'barrier' => 'lift_gate', 'name' => 'a'}, 'closed_way', false, 22..22, 'master', 'master') #catcha-all for areas #missing label #CartoCSSHelper::VisualDiff.visualise_changes_synthethic_test({'tourism' => 'viewpoint', 'name' => 'a'}, 'closed_way', false, 22..22, 'master', 'master') #TODO watchlist =begin rescue todo - watchlist for rare landuse values in Kraków, ; w surface http://wiki.openstreetmap.org/wiki/Tag%3Alanduse%3Ddepot - update http://overpass-turbo.eu/s/aJA access=public eliminator #http://overpass-turbo.eu/s/aJm - reduce impact before rendering proposal CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'parking', 'access'=>'public'}, 'public', 'master', 13..19, 'way', 2) CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'parking', 'access'=>'private'}, 'public', 'master', 13..19, 'way', 2) CartoCSSHelper.test_tag_on_real_data_for_this_type({'amenity' => 'parking', 'access'=>'yes'}, 'public', 'master', 13..19, 'way', 2) =end #CartoCSSHelper::Validator.run_tests('v2.34.0') #merged #before_after_from_loaded_databases({'amenity' => 'car_wash'}, 'kocio/car_wash', 'master', 14..22, 375, 5) #CartoCSSHelper.test ({'amenity' => 'car_wash'}), 'kocio/car_wash', 'master', 14..22 z = 14..18 #missing name #CartoCSSHelper::VisualDiff.visualise_changes_synthethic_test({'natural' => 'peak', 'ele' => '4'}, 'node', false, 22..22, 'v2.31.0', 'v2.30.0') # 24, 29 - 34 #CartoCSSHelper::VisualDiff.visualise_changes_synthethic_test({'natural' => 'peak', 'ele' => '4', 'name' => 'name'}, 'node', false, 22..22, 'v2.34.0', 'v2.34.0') #CartoCSSHelper::VisualDiff.visualise_changes_synthethic_test({'aeroway' => 'gate', 'ref' => '4'}, 'node', false, 22..22, 'v2.31.0', 'v2.30.0') # 20, 27, 29, 30 - 31 34 #before_after_from_loaded_databases({'aeroway' => 'gate', 'ref' => :any_value}, 'v2.31.0', 'v2.30.0', 22..22, 100, 2) #CartoCSSHelper.test_tag_on_real_data({'aeroway' => 'gate', 'ref' => :any_value}, 'v2.31.0', 'v2.30.0', 22..22, ['way'], 2) final show_fixed_bugs(branch) large_scale_diff(branch, master) test_low_invisible(branch, master) generate_preview(['master']) final CartoCSSHelper::VisualDiff.enable_job_pooling gsoc_places(frozen_trunk, frozen_trunk, 10..18) CartoCSSHelper::VisualDiff.shuffle_jobs(8) final =begin branch = frozen_trunk [11..19].each {|zlevels| #19..19, 15..15, 11..11, get_all_road_types.each { |tag| before_after_from_loaded_databases({'highway' => tag, 'bridge' => 'yes'}, branch, branch, zlevels) before_after_from_loaded_databases({'highway' => tag, 'tunnel' => 'yes'}, branch, branch, zlevels) before_after_from_loaded_databases({'highway' => tag}, branch, branch, zlevels) } } =end [11,10,9,8].each{|z| ['55c4b27', master].each {|branch| #new-road-style image_size = 780 if z <= 6 image_size = 300 end #get_single_image_from_database('world', branch, 50.8288, 4.3684, z, 300, "Brussels #{branch}") #get_single_image_from_database('world', branch, -36.84870, 174.76135, z, 300, "Auckland #{branch}") #get_single_image_from_database('world', branch, 39.9530, -75.1858, z, 300, "New Jersey #{branch}") #get_single_image_from_database('world', branch, 55.39276, 13.29790, z, 300, "Malmo - fields #{branch}") get_single_image_from_database('world', branch, 50, 40, z, image_size, "Russia interior #{branch}") get_single_image_from_database('world', branch, 50, 20, z, image_size, "Krakow #{branch}") get_single_image_from_database('world', branch, 35.07851, 137.684848, z, image_size, "Japan #{branch}") if z < 10 #nothing interesting on z11+ get_single_image_from_database('world', branch, -12.924, -67.841, z, image_size, "South America #{branch}") get_single_image_from_database('world', branch, 50, 0, z, image_size, "UK, France #{branch}") end get_single_image_from_database('world', branch, 16.820, 79.915, z, image_size, "India #{branch}") before_after_directly_from_database('world', 53.8656, -0.6659, branch, branch, z..z, image_size, "rural UK #{branch}") before_after_directly_from_database('world', 64.1173, -21.8688, branch, branch, z..z, image_size, "Iceland, Reykjavik #{branch}") } } image_size = 780 [6, 5, 7].each{|z| ['55c4b27', master].each {|branch| #get_single_image_from_database('world', branch, 50.8288, 4.3684, z, 300, "Brussels #{branch}") #get_single_image_from_database('world', branch, -36.84870, 174.76135, z, 300, "Auckland #{branch}") #get_single_image_from_database('world', branch, 39.9530, -75.1858, z, 300, "New Jersey #{branch}") #get_single_image_from_database('world', branch, 55.39276, 13.29790, z, 300, "Malmo - fields #{branch}") get_single_image_from_database('world', branch, 50, 40, z, image_size, "Russia interior #{branch}") get_single_image_from_database('world', branch, 50, 20, z, image_size, "Krakow #{branch}") get_single_image_from_database('world', branch, 35.07851, 137.684848, z, image_size, "Japan #{branch}") if z < 10 #nothing interesting on z11+ get_single_image_from_database('world', branch, -12.924, -67.841, z, image_size, "South America #{branch}") get_single_image_from_database('world', branch, 50, 0, z, image_size, "UK, France #{branch}") end get_single_image_from_database('world', branch, 16.820, 79.915, z, image_size, "India #{branch}") before_after_directly_from_database('world', 53.8656, -0.6659, branch, branch, z..z, image_size, "rural UK #{branch}") before_after_directly_from_database('world', 64.1173, -21.8688, branch, branch, z..z, image_size, "Iceland, Reykjavik #{branch}") } } gsoc_places('trunk', 'gsoc', 9..18) CartoCSSHelper::VisualDiff.shuffle_jobs(8) #show_fixed_bugs('gsoc') final test_low_invisible(branch, branch) CartoCSSHelper.visualise_place_by_url('http://www.openstreetmap.org/?mlat=53.149497&mlon=-6.3292126', 16..16, branch, 'master', 'bog', 0.1) test_tag_on_real_data_pair_for_this_type({'highway'=>'pedestrian'}, {'highway' => 'living_street'}, branch, 'master', 17..17, 'way', 2, 5, 375) test_tag_on_real_data_pair_for_this_type({'natural'=>'heath'}, {'highway' => 'secondary', 'ref' => :any_value}, branch, 'master', 16..16, 'way', 2, 6, 375) test_tag_on_real_data_pair_for_this_type({'natural'=>'beach'}, {'highway' => 'secondary'}, branch, 'master', 17..17, 'way', 2, 6, 375) test_tag_on_real_data_pair_for_this_type({'natural'=>'sand'}, {'highway' => 'secondary'}, branch, 'master', 17..17, 'way', 1, 72, 375) test_tag_on_real_data_pair_for_this_type({'natural'=>'wetland', 'wetland' => 'bog'}, {'highway' => 'secondary', 'ref' => :any_value}, branch, 'master', 17..17, 'way', 1, 72, 375) before_after_directly_from_database('world', 47.1045, -122.5882, branch, 'master', 9..10, 375) before_after_directly_from_database('rome', 41.92054, 12.48020, branch, 'master', 12..19, 375) before_after_directly_from_database('rome', 41.85321, 12.44090, branch, 'master', 12..19, 375) large_scale_diff(branch, 'master') before_after_directly_from_database('krakow', 50.08987, 19.89922, branch, 'master', 12..19, 375) generate_preview([branch]) CartoCSSHelper::VisualDiff.enable_job_pooling gsoc_places(branch, branch, 7..17) CartoCSSHelper::VisualDiff.run_jobs gsoc_full(branch, branch, 7..17) CartoCSSHelper::VisualDiff.shuffle_jobs(4) CartoCSSHelper::VisualDiff.run_jobs (5..19).each { |zlevel| CartoCSSHelper::Grid.new(zlevel, branch, road_set(true, true), areas_set) } test_all_road_types(branch) CartoCSSHelper::VisualDiff.run_jobs base_test(to) CartoCSSHelper::VisualDiff.run_jobs CartoCSSHelper::Validator.run_tests('v2.32.0') end end # additional_test_unpaved('master', 'master') #not great, not terrribe #test_tag_on_real_data_pair_for_this_type({'natural'=>'heath'}, {'highway' => 'secondary', 'ref' => :any_value}, 'new-road-style', 'new-road-style', 16..16, 'way') #test_tag_on_real_data_pair_for_this_type({'natural'=>'wetland', 'wetland' => 'bog'}, {'highway' => 'secondary', 'ref' => :any_value}, 'new-road-style', 'new-road-style', 17..17, 'way') #test_airport_unify def notify(text, silent=$silent) if silent return end puts "Notification: #{text}" system("notify-send '#{text}'") end def notify_spam(text) while true notify text sleep 10 end end def done_segment notify 'Computed!' end def final CartoCSSHelper::VisualDiff.run_jobs notify_spam 'Everything computed!' exit end #create_databases() begin make_copy_of_repository = false init(make_copy_of_repository) #CartoCSSHelper::Configuration.set_known_alternative_overpass_url main rescue => e puts e puts puts e.backtrace notify_spam('Crash during map generation!') end #poszukać carto w efektywność
require "test_helper" describe OrderItemsController do let (:product1) { products(:cake1) } let (:product2) { products(:cake3) } let (:order_item_hash1) { { order_item: { product_id: product1.id, qty: 5 } } } let (:order_item_hash2) { { order_item: { product_id: product2.id, qty: 3 } } } let (:exceeds_inventory) { { order_item: { product_id: product1.id, qty: 8 } } } let (:update_order_item1) { { order_item: { product_id: product1.id, qty: 3 } } } let (:invalid_data) { { order_item: { product_id: product1.id, qty: nil } } } describe 'create' do it 'can create a new order line item when order does not already exist' do orders_before = Order.count expect { post order_items_path, params: order_item_hash1 }.must_change 'OrderItem.count', 1 orders_after = Order.count order_id = Order.last.id must_respond_with :redirect must_redirect_to cart_path(order_id) expect(orders_after).must_equal orders_before + 1 expect(OrderItem.last.product_id).must_equal product1.id expect(OrderItem.last.order_id).must_equal order_id end it 'can create a new order line item to existing order' do post order_items_path, params: order_item_hash1 order_id = Order.last.id expect { post order_items_path, params: order_item_hash2 }.must_change 'OrderItem.count', 1 must_respond_with :redirect must_redirect_to cart_path(order_id) expect(OrderItem.last.product_id).must_equal product2.id expect(OrderItem.last.order_id).must_equal order_id end it 'can not add a line order item if quantity exceeds inventory' do expect { post order_items_path, params: exceeds_inventory }.wont_change 'OrderItem.count' must_respond_with :redirect must_redirect_to product_path(product1.id) end end describe 'update' do before do post order_items_path, params: order_item_hash1 @order_id = Order.last.id @order_item_id = OrderItem.last.id @before_qty = OrderItem.find_by(id: @order_item_id).qty end it 'can update an existing order line item with valid data' do expect { patch order_item_path(@order_item_id), params: update_order_item1 }.wont_change 'OrderItem.count' after_qty = OrderItem.find_by(id: @order_item_id).qty expect(after_qty).must_equal update_order_item1[:order_item][:qty] must_respond_with :redirect must_redirect_to cart_path(@order_id) end it 'will not update an existing order line item with invalid data' do expect { patch order_item_path(@order_item_id), params: invalid_data }.wont_change 'OrderItem.count' after_qty = OrderItem.find_by(id: @order_item_id).qty expect(after_qty).must_equal @before_qty must_respond_with :redirect must_redirect_to root_path end it 'will redirect when a line order item does not exist to update' do expect { patch order_item_path(-1), params: update_order_item1 }.wont_change 'OrderItem.count' must_respond_with :redirect must_redirect_to root_path end it 'will will not update existing order line item when qty exceeds inventory count' do expect { patch order_item_path(@order_item_id), params: exceeds_inventory }.wont_change 'OrderItem.count' after_qty = OrderItem.find_by(id: @order_item_id).qty expect(after_qty).must_equal @before_qty must_respond_with :redirect must_redirect_to product_path(product1.id) end end describe 'destroy' do before do post order_items_path, params: order_item_hash1 @order_id = Order.last.id @order_item_id = OrderItem.last.id @before_qty = OrderItem.find_by(id: @order_item_id).qty end it 'can delete an existing order line item' do expect{ delete order_item_path(@order_item_id) }.must_change 'OrderItem.count', -1 must_respond_with :redirect must_redirect_to cart_path(@order_id) expect(OrderItem.find_by(id: @order_item_id)).must_be_nil end it 'will render not_found when a line order item does not exist to delete' do end end describe 'cart_direct' do it 'can add a line order item with a qty of 1 when existing order exists' do post order_items_path, params: order_item_hash1 order_id = Order.last.id new_item = products(:cake3) expect { post quick_shop_path(new_item.id) }.must_change 'OrderItem.count', 1 must_respond_with :redirect must_redirect_to cart_path(order_id) expect(OrderItem.last.product_id).must_equal new_item.id expect(OrderItem.last.order_id).must_equal order_id end it 'can add a line order item with a qty of 1 when existing order does not exist' do orders_before = Order.count new_item = products(:cake3) expect { post quick_shop_path(new_item.id) }.must_change 'OrderItem.count', 1 orders_after = Order.count order_id = Order.last.id must_respond_with :redirect must_redirect_to cart_path(order_id) expect(orders_after).must_equal orders_before + 1 expect(OrderItem.last.product_id).must_equal new_item.id expect(OrderItem.last.order_id).must_equal order_id end it 'can not add a line order item if item is out of stock' do product = products(:brownie) expect { post quick_shop_path(product.id) }.wont_change 'OrderItem.count' must_respond_with :redirect must_redirect_to products_path end end end
json.array!(@sites) do |sites| json.extract! sites, :id, :name, :url, :rss_url end
# -*- encoding : utf-8 -*- module Retailigence #:nodoc: # Raised when Retailigence doesn't find any results class NoResults < StandardError; end # Raised when any other exception occurs from the API class APIException < StandardError; end end
class CreateQuestions < ActiveRecord::Migration def up create_table :questions do |t| t.references :control, :null => false t.string :name t.string :description t.integer :answer_id t.timestamps end add_foreign_key :questions, :controls end def down drop_table :questions end end
class UpNickLimit < ActiveRecord::Migration def change change_column :users, :Nick, :text end end
class CreateActions < ActiveRecord::Migration def change create_table(:actions) do |t| t.string :parent_type t.integer :parent_id t.string :name t.string :link t.string :target t.text :requirements t.text :outcomes end end end
require 'rails_helper' RSpec.describe VotesController, type: :controller do describe '#create' do let(:voteable) { FactoryBot.create(:article) } let(:user) { FactoryBot.create(:user) } let(:params) do { voteable_id: voteable.id, voteable_type: voteable.class.to_s } end context 'when not logged in' do it 'does not increment karma' do post :create, params: params voteable.reload expect(voteable.karma).to eq(1) end end context 'when logged in' do before { sign_in user } it 'increments karma' do post :create, params: params voteable.reload expect(voteable.karma).to eq(2) end it 'creates a vote record' do post :create, params: params vote = Vote.find_by(user: user, voteable_id: voteable.id, voteable_type: voteable.class.to_s) expect(vote).not_to be_nil end it 'will not increment more than once' do post :create, params: params post :create, params: params voteable.reload expect(voteable.karma).to eq(2) end end end describe '#delete' do before { vote } let(:voteable) { FactoryBot.create(:article) } let(:user) { FactoryBot.create(:user) } let(:vote) { FactoryBot.create(:vote, user: user, voteable: voteable) } let(:params) do { voteable_id: voteable.id, voteable_type: voteable.class.to_s } end context 'when not logged in' do it 'does not decrement karma' do delete :destroy, params: params voteable.reload expect(voteable.karma).to eq(1) end end context 'when logged in' do before { sign_in user } it 'decrements karma' do delete :destroy, params: params voteable.reload expect(voteable.karma).to eq(0) end it 'deletes the vote record' do delete :destroy, params: params vote = Vote.find_by(user: user, voteable_id: voteable.id, voteable_type: voteable.class.to_s) expect(vote).to be_nil end it 'will not decrement more than once' do delete :destroy, params: params delete :destroy, params: params voteable.reload expect(voteable.karma).to eq(0) end end end end
# == Schema Information # # Table name: users # # id :bigint not null, primary key # user_name :string not null # password_digest :string not null # session_token :string not null # created_at :datetime not null # updated_at :datetime not null # class User < ApplicationRecord require 'securerandom' def reset_session_token! self.update!(session_token: self.class.generate_session_token) self.session_token end def password=(password) self.password_digest = BCrypt::Password.create(password) end end
class Longtask < Simpletask validates :porcentaje, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 100, message: "debe ser entre 0 y 100" } end
require 'yaml' module SidekiqRunner class SidekiqConfiguration include Enumerable RUNNER_ATTRIBUTES = [:config_file] RUNNER_ATTRIBUTES.each { |att| attr_accessor att } attr_reader :sidekiqs def initialize @config_file = if defined?(Rails) File.join(Rails.root, 'config', 'sidekiq.yml') else File.join(Dir.pwd, 'config', 'sidekiq.yml') end @sidekiqs = {} end def self.default @default ||= SidekiqConfiguration.new end def self.get config = default.dup config.merge_config_file! config.sane? config end def each(&block) @sidekiqs.each(&block) end def each_key(&block) @sidekiqs.each_key(&block) end def empty? @sidekiqs.empty? end def add_instance(name) fail "Sidekiq instance with the name '#{name}' already exists! No duplicates please." if @sidekiqs.key?(name) @sidekiqs[name] = SidekiqInstance.new(name) yield @sidekiqs[name] if block_given? end # Top-level single instance configuration methods, partially for backward compatibility. (SidekiqInstance::CONFIG_FILE_ATTRIBUTES + SidekiqInstance::RUNNER_ATTRIBUTES).each do |meth| define_method("#{meth}=") do |val| ensure_default_sidekiq! @sidekiqs.each { |_, skiq| skiq.send("#{meth}=", val) } end end def queue(name, weight = 1) fail 'Multiple Sidekiq instances defined and queue() outside of instance block called.' if @sidekiqs.size > 1 ensure_default_sidekiq! @sidekiqs.values.first.add_queue(name, weight) end alias_method :add_queue, :queue alias_method :configfile=, :config_file= # Callbacks. %w(start stop).each do |action| %w(success error).each do |state| attr_reader "#{action}_#{state}_cb".to_sym define_method("on_#{action}_#{state}") do |&block| instance_variable_set("@#{action}_#{state}_cb".to_sym, block) end end end def ensure_default_sidekiq! add_instance('sidekiq_default') if empty? end def merge_config_file! sidekiqs_common_config = {} yml = File.exist?(config_file) ? YAML.load_file(config_file) : {} yml = Hash[yml.map { |k, v| [k.to_sym, v] }] @sidekiqs.each_value { |skiq| skiq.merge_config_file!(yml) } end def sane? fail 'No sidekiq instances defined. Nothing to run.' if @sidekiqs.empty? fail 'Sidekiq instances with the same pidfile found.' if @sidekiqs.values.map(&:pidfile).uniq.size < @sidekiqs.size fail 'Sidekiq instances with the same logfile found.' if @sidekiqs.values.map(&:logfile).uniq.size < @sidekiqs.size @sidekiqs.each_value { |skiq| skiq.sane? } end end end
class JobsController < ApplicationController def index @q = JobPosting.current_jobs.ransack(params[:q]) @jobs = @q.result(distinct: true) end def show @job = JobPosting.find(params[:id]) end def create @job = JobPosting.new(job_params) if @job.save redirect_to job_path(@job), notice: "Your job listing has been posted." else render :new end end def new @job = JobPosting.new() end private def job_params params.require(:job_posting).permit( :company, :title, :description, :how_to_apply, :full_time ) end end
class WeatherDependency include Mongoid::Document store_in client: 'labels' field :clear_sky, type: Boolean, default: false field :dew_point, type: Boolean, default: false field :humidity, type: Boolean, default: false field :precipitation, type: Boolean, default: false field :pressure, type: Boolean, default: false field :temperature, type: Boolean, default: false field :visibility, type: Boolean, default: false field :wind, type: Boolean, default: false field :clear_sky_max_temp, type: Integer #temperature in Celsius degree field :dew_point_temp_difference, type: Integer #temperature in Celsius degree field :humidity_min, type: Float # 0-1 field :humidity_max, type: Float # 0-1 field :precip_intensity_max, type: Float # field :precip_type, type: String # rain, snow or sleet field :precip_probability, type: Float, default: 0.1 field :pressure_max, type: Integer field :pressure_min, type: Integer field :temperature_min, type: Integer field :temperature_max, type: Integer field :temperature_max_difference, type: Integer field :visibility_min, type: Integer field :wind_speed_max, type: Float embedded_in :weather_preset before_validation :set_dew_point_temperature validates :humidity_max, :humidity_min, :precip_probability, inclusion: 0..1, allow_nil: true validates :visibility_min, inclusion: 0..1000, allow_nil: true validates :clear_sky_max_temp, :temperature_max, :temperature_min, :temperature_max_difference, inclusion: -30..80, allow_nil: true validates :clear_sky_max_temp, presence: true, if: :clear_sky validates :dew_point_temp_difference, presence: true, if: :dew_point validates :precip_intensity_max, :precip_probability, presence: true, if: :precipitation validates :precip_type, inclusion: %w(rain snow sleet), allow_nil: true validates :visibility_min, presence: true, if: :visibility validates :wind_speed_max, inclusion: 0..36, allow_nil: true validates :wind_speed_max, presence: true, if: :wind validate :validate_humidity validate :validate_pressure validate :validate_temperatures def merge(dependencies) dependencies = Array(dependencies) return self unless dependencies.any? dependencies << self [:clear_sky, :dew_point, :humidity, :precipitation, :pressure, :temperature, :visibility].each do |field| self.send "#{field}=", dependencies.map { |dependency| dependency.send field }.any? end [:clear_sky_max_temp, :dew_point_temp_difference, :humidity_max, :precip_intensity_max, :pressure_max, :temperature_max, :temperature_max_difference, :visibility_min].each do |field| values = dependencies.map { |dependency| dependency.send field } value = values.any? ? values.min : nil self.send "#{field}=", value end [:humidity_min, :pressure_min, :temperature_min].each do |field| values = dependencies.map { |dependency| dependency.send field } value = values.any? ? values.max : nil self.send "#{field}=", value end percip_types = dependencies.map { |dependency| dependency.percip_type } if percip_types.include? 'sleet' self.percip_type = 'sleet' elsif percip_types.include? 'snow' self.percip_type = 'snow' else self.percip_type = 'rain' end self end def any? clear_sky || dew_point || humidity || precipitation || pressure || temperature || visibility || wind end private def validate_temperatures if temperature && ![temperature_max, temperature_min, temperature_max_difference].any? errors[:temperature] = :no_values end end def validate_pressure if pressure && ![pressure_max, pressure_min].any? errors[:pressure] = :no_values end end def validate_humidity if pressure && ![humidity_max, humidity_min].any? errors[:humidity] = :no_values end end def set_dew_point_temperature if dew_point self.dew_point_temp_difference ||= 0 else self.dew_point_temp_difference = nil end end end
# frozen_string_literal: true require "English" require "net/http" unless LightStep::VERSION == '0.10.9' raise <<-MSG This monkey patch needs to be reviewed for LightStep versions other than 0.10.9. To review, diff the changes between the `LightStep::Transport::HTTPJSON#report` method and the `HubStep::Transport::HTTPJSON#report` method below and port any changes that seem necessary. MSG end module HubStep module Transport # HTTPJSON is a transport that sends reports via HTTP in JSON format. # It is thread-safe, however it is *not* fork-safe. When forking, all items # in the queue will be copied and sent in duplicate. # # When forking, you should first `disable` the tracer, then `enable` it from # within the fork (and in the parent post-fork). See # `examples/fork_children/main.rb` for an example. class HTTPJSON < LightStep::Transport::HTTPJSON # Queue a report for sending def report(report) # rubocop:disable Metrics/AbcSize,Metrics/MethodLength p report if @verbose >= 3 HubStep.instrumenter.instrument('lightstep.transport.report', {}) do |payload| https = Net::HTTP.new(@host, @port) https.use_ssl = @encryption == ENCRYPTION_TLS req = Net::HTTP::Post.new('/api/v0/reports') req['LightStep-Access-Token'] = @access_token req['Content-Type'] = 'application/json' req['Connection'] = 'keep-alive' req.body = report.to_json res = https.request(req) payload[:request_body] = req.body puts res.to_s, res.body if @verbose >= 3 payload[:response] = res end nil rescue => e HubStep.instrumenter.instrument('lightstep.transport.error', error: e) end end end end
require 'rspec' require_relative '../../src/stm' require_relative 'concurrently' require_relative 'real_bank_account' describe 'Testing BankAccount operations' do def expect_balance(account_sym, expected_balance) balance_msg = Proc.new do |account_sym, expected| "El balance de #{account_sym} es #{instance_variable_get(account_sym).balance}, en lugar de #{expected}" end expect(instance_variable_get(account_sym).balance).to eq(expected_balance), balance_msg.call(account_sym, expected_balance) end before do if RUBY_ENGINE == 'rbx' skip 'Rubinius VM crashes when executing this real life example.' end @an_account = RealBankAccount.new(40) @another_account = RealBankAccount.new(10) end it 'should withdraw from an account multiple times correctly' do concurrently(20) do Proc.new do @an_account.withdraw(2) end.atomic_retry end expect_balance(:@an_account, 0) end it 'should transfer from an account to another correctly', :aggregate_failures do concurrently(20) do Proc.new do @an_account.transfer_to(2, @another_account) end.atomic_retry end expect_balance(:@an_account, 0) expect_balance(:@another_account, 50) end it 'should transfer an account to another one AND BACK TO THE ORIGINAL correctly', :aggregate_failures do concurrently(20) do Proc.new do @an_account.transfer_to(2, @another_account) @another_account.transfer_to(2, @an_account) end.atomic_retry end expect_balance(:@an_account, 40) expect_balance(:@another_account, 10) end end
class CreatePhase5 < ActiveRecord::Migration def change create_table :phase5s do |t| t.string :mobile_responsive t.string :mobile_contact_info t.string :mobile_phone_number t.string :mobile_directions t.string :mobile_font_size t.string :mobile_buttons t.string :mobile_navigation t.string :mobile_structure t.integer :business_id t.timestamps end end end
require "spec_helper" class MyLogger; end class MyDbConnection; def exec; end; end class MyQueue; end describe PgQueue do before do described_class.connection = MyDbConnection.new described_class.logger = Logger.new("/dev/null") end context "logging" do before do described_class.logger = nil end after do described_class.logger = nil end it "defines a logger" do described_class.logger.should be_instance_of(Logger) described_class.logger = MyLogger.new described_class.logger.should be_instance_of(MyLogger) end end context "database connection" do its(:connection) { should be_instance_of(MyDbConnection) } context "extensions" do subject { described_class.connection } it { should respond_to(:insert) } it { should respond_to(:notify) } it { should respond_to(:delete) } it { should respond_to(:first) } it { should respond_to(:listen) } it { should respond_to(:unlisten) } it { should respond_to(:new_connection) } end end context "interval" do after do described_class.interval = nil end it "defines the interval" do described_class.interval.should == 0 described_class.interval = 5 described_class.interval.should == 5 end end context "enqueuing/dequeuing" do let(:connection) { described_class.connection } let(:result) { double("result") } it "enqueues a job" do connection.should_receive(:insert).with(:pg_queue_jobs, instance_of(Hash), "id").and_return("1") connection.should_receive(:notify).with(:pg_queue_jobs) described_class.enqueue(MyQueue, 1, "two") end it "dequeues a job" do connection.should_receive(:first).with(/LIMIT 1/).and_return(result) result.should_receive(:[]).with("id").and_return("1") result.should_receive(:[]).with("class_name").and_return("MyQueue") result.should_receive(:[]).with("args").and_return("[1, \"two\"]") connection.should_receive(:delete).with(:pg_queue_jobs, :id => "1") subject.dequeue.should be_instance_of(PgQueue::Job) end end end
class Event < ApplicationRecord include ActiveModel::Validations has_many :users_events, dependent: :destroy has_many :users, through: :users_events # @event.users validates_presence_of :title, :category, :address, :city, :state, :zip, :time, :about_content validates :zip, length: { is: 5 } validates_numericality_of :zip # validate :date_must_be_after_today validates_with DateValidator, on: :create scope :future_date, lambda { where("date > ?", Date.today) } # ARel query? # scope allows you to specify an ARel query that can be used as a method call to the model (or association objects) # equivalent to: scope :order_by_date, -> {order("date")} # scope :users_state, -> { where("state" == )} # def date_must_be_after_today #(((this method went into DateValidator))) # if date <= Time.now # errors.add(:date, "must be after today") # end # end def is_admin?(user) self.users_events.where(admin: true).pluck(:user_id).include?(user.id) end def self.search(params) # @events = Event.order_by_date.where("(title || about_content || category) LIKE ?", "%" + params[:search] + "%") # ^case sensitive in PG^ or (below) can only search one attr/field # @events = Event.order_by_date.where(Event.arel_table[:title].matches("%#{params[:search]}%")) #https://www.scimedsolutions.com/blog/arel-part-i-case-insensitive-searches-with-partial-matching @events = Event.order_by_date.where( %i(title category about_content state) .map { |field| Event.arel_table[field].matches("%#{params[:search]}%")} .inject(:or) ) #https://www.thetopsites.net/article/53226084.shtml end end
class CreateBills < ActiveRecord::Migration def change create_table :bills do |t| t.column :name, :string, :null => false t.column :description, :string t.column :user_id, :integer, :foreign_key => true #ou então t.reference :users, :foreign_key => true t.column :date, :datetime, :null => false t.column :value, :decimal end end end
require "rails_helper" describe Team do let(:attributes) do { name: "lakeshow", city: "LA", mascot: "Lake" } end # # # it "is considered valid" do # # expect(Team.new(attributes)).to be_valid # # end let(:missing_name) { attributes.except(:name) } let(:missing_city) { attributes.except(:city) } let(:missing_mascot) { attributes.except(:mascot) } let(:missing_point_guard) { attributes.except(:point_guard_id) } let(:missing_shooting_guard) { attributes.except(:shooting_guard_id) } let(:missing_small_forward) { attributes.except(:small_forward_id) } let(:missing_power_forward) { attributes.except(:power_forward_id) } let(:missing_center) { attributes.except(:center_id) } it "is invalid without a name" do expect(Team.new(missing_name)).not_to be_valid end it "is invalid without a city" do expect(Team.new(missing_city)).not_to be_valid end it "is invalid without a mascot" do expect(Team.new(missing_mascot)).not_to be_valid end it "is invalid without a point guard" do expect(Team.new(missing_point_guard)).not_to be_valid end it "is invalid without a shooting guard" do expect(Team.new(missing_shooting_guard)).not_to be_valid end it "is invalid without a small forward" do expect(Team.new(missing_small_forward)).not_to be_valid end it "is invalid without a power forward" do expect(Team.new(missing_power_forward)).not_to be_valid end it "is invalid without a center" do expect(Team.new(missing_center)).not_to be_valid end end
Pod::Spec.new do |s| s.name = "SSKeychain" s.summary = "SSKeychain is a simple wrapper for using the system Keychain on Mac OS X and iOS." s.version = "1.2.2" s.license = 'MIT' s.homepage = 'https://github.com/soffes/sskeychain' s.author = { 'Sam Soffes' => 'sam@soff.es' } s.source = { :http => "http://repository.neonstingray.com/content/repositories/thirdparty/com/sskeychain/ios/sskeychain/1.2.2/sskeychain-1.2.2.zip" } s.platform = :ios s.frameworks = 'Security', 'Foundation' s.source_files = 'SSKeychain/*.{h,m}' s.requires_arc = true end
require File.dirname(__FILE__) + "/spec_helper" describe Sequel::Schema::DbColumn do before :each do @column = Sequel::Schema::DbColumn.new(:foo, :integer, false, 10, true, 10, nil) end it "should return a #define_statement" do expect(@column.define_statement).to eql("integer :foo, :null => false, :default => 10, :unsigned => true, :size => 10") end it "should return a primary_key invocation if single_primary_key is set and the column is an integer" do @column.single_primary_key = true expect(@column.define_statement).to eql("primary_key :foo, :type => :integer, :null => false, :default => 10, :unsigned => true, :size => 10") end it "should return a #drop_statement" do expect(@column.drop_statement).to eql("drop_column :foo") end it "should return an #add_statement" do expect(@column.add_statement).to eql("add_column :foo, :integer, :null => false, :default => 10, :unsigned => true, :size => 10") end it "should return a #change_null statement" do expect(@column.change_null_statement).to eql("set_column_allow_null :foo, false") end it "should return a #change_default statement" do expect(@column.change_default_statement).to eql("set_column_default :foo, 10") end it "should return a #change_type statement" do expect(@column.change_type_statement).to eql("set_column_type :foo, :integer, :default => 10, :unsigned => true, :size => 10") end it "should be diffable with another DbColumn" do other = Sequel::Schema::DbColumn.new(:foo, :smallint, false, 10, true, 10, nil) expect(@column.diff(other)).to eql([:column_type].to_set) other = Sequel::Schema::DbColumn.new(:foo, :integer, true, 11, true, 10, nil) expect(@column.diff(other)).to eql([:null, :default].to_set) end it "should not consider allowing null being nil different from false" do a = Sequel::Schema::DbColumn.new(:foo, :smallint, false, 10, true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :smallint, nil, 10, true, 10, nil) expect(a.diff(b)).to be_empty expect(b.diff(a)).to be_empty end it "should not consider size to be different if one of the sizes is nil" do a = Sequel::Schema::DbColumn.new(:foo, :smallint, false, 10, true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :smallint, false, 10, true, nil, nil) expect(a.diff(b)).to be_empty expect(b.diff(a)).to be_empty end it "should not consider 0 to be different from null if the column does not allow nulls" do a = Sequel::Schema::DbColumn.new(:foo, :smallint, false, 0, true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :smallint, false, nil, true, nil, nil) expect(a.diff(b)).to be_empty expect(b.diff(a)).to be_empty end it "should consider 0 to be different from null if the column does allow nulls" do a = Sequel::Schema::DbColumn.new(:foo, :smallint, true, 0, true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :smallint, true, nil, true, nil, nil) expect(a.diff(b)).to eql([:default].to_set) expect(b.diff(a)).to eql([:default].to_set) end it "should consider 1 to be different from null" do a = Sequel::Schema::DbColumn.new(:foo, :smallint, false, 1, true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :smallint, false, nil, true, nil, nil) expect(a.diff(b)).to eql([:default].to_set) expect(b.diff(a)).to eql([:default].to_set) end it "should not consider '' to be different from null if the column does not allow nulls" do a = Sequel::Schema::DbColumn.new(:foo, :varchar, false, '', true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :varchar, false, nil, true, nil, nil) expect(a.diff(b)).to be_empty expect(b.diff(a)).to be_empty end it "should consider '' to be different from null if the column allows null" do a = Sequel::Schema::DbColumn.new(:foo, :varchar, true, '', true, 10, nil) b = Sequel::Schema::DbColumn.new(:foo, :varchar, true, nil, true, nil, nil) expect(a.diff(b)).to eql([:default].to_set) expect(b.diff(a)).to eql([:default].to_set) end it "should consider columns with different elements to be different" do a = Sequel::Schema::DbColumn.new(:foo, :enum, true, nil, true, nil, ["A"]) b = Sequel::Schema::DbColumn.new(:foo, :enum, true, nil, true, nil, ["A", "B"]) expect(a.diff(b)).to eql([:elements].to_set) expect(b.diff(a)).to eql([:elements].to_set) end it "should cast decimal defaults to the correct number" do a = Sequel::Schema::DbColumn.new(:foo, :decimal, true, '0.00', true, [4,2], nil) b = Sequel::Schema::DbColumn.new(:foo, :decimal, true, 0, true, [4,2], nil) expect(a.diff(b)).to eql(Set.new) expect(b.diff(a)).to eql(Set.new) end it "should output BigDecimal correctly in a #define_statement" do expect(Sequel::Schema::DbColumn.new(:foo, :decimal, false, '1.1', true, [4,2], nil).define_statement).to eql("decimal :foo, :null => false, :default => BigDecimal.new('1.1'), :unsigned => true, :size => [4, 2]") end it "should be buildable from a Hash" do expect(Sequel::Schema::DbColumn.build_from_hash(:name => "foo", :column_type => "integer").column_type).to eql("integer") expect(Sequel::Schema::DbColumn.build_from_hash('name' => "foo", 'column_type' => "integer").name).to eql("foo") end end
require "strscan" class QueryTokenizer def tokenize(str) tokens = [] @warnings = [] s = StringScanner.new(str) until s.eos? if s.scan(/[\s,]+/i) # pass elsif s.scan(/and\b/i) # and is default, skip it elsif s.scan(/or\b/i) tokens << [:or] elsif s.scan(%r[(R&D\b)]i) # special case, not split cards tokens << [:test, ConditionWord.new(s[1])] elsif s.scan(%r[(\bDungeons\s*&\s*Dragons\b)]i) # special case, not split cards tokens << [:test, ConditionWord.new(s[1])] elsif s.scan(%r[[/&]+]i) tokens << [:slash_slash] elsif s.scan(/-/i) tokens << [:not] elsif s.scan(/\(/i) tokens << [:open] elsif s.scan(/\)/i) tokens << [:close] elsif s.scan(%r[ (o|oracle|ft|flavor|a|art|artist|n|name|number|rulings) \s*[:=]\s* /( (?:[^\\/]|\\.)* )/ ]xi) begin cond = { "a" => ConditionArtistRegexp, "art" => ConditionArtistRegexp, "artist" => ConditionArtistRegexp, "ft" => ConditionFlavorRegexp, "flavor" => ConditionFlavorRegexp, "n" => ConditionNameRegexp, "name" => ConditionNameRegexp, "o" => ConditionOracleRegexp, "oracle" => ConditionOracleRegexp, "number" => ConditionNumberRegexp, "rulings" => ConditionRulingsRegexp, }[s[1].downcase] or raise "Internal Error: #{s[0]}" rx = Regexp.new(s[2], Regexp::IGNORECASE | Regexp::MULTILINE) tokens << [:test, cond.new(rx)] rescue RegexpError => e cond = { "a" => ConditionArtist, "art" => ConditionArtist, "artist" => ConditionArtist, "ft" => ConditionFlavor, "flavor" => ConditionFlavor, "n" => ConditionWord, "name" => ConditionWord, "o" => ConditionOracle, "oracle" => ConditionOracle, "number" => ConditionNumber, "rulings" => ConditionRulings, }[s[1].downcase] or raise "Internal Error: #{s[0]}" @warnings << "bad regular expression in #{s[0]} - #{e.message}" tokens << [:test, cond.new(s[2])] end elsif s.scan(%r[ (cn|tw|fr|de|it|jp|kr|pt|ru|sp|cs|ct|foreign) \s*[:=]\s* /( (?:[^\\/]|\\.)* )/ ]xi) begin # Denormalization is highly questionable here rxstr = s[2].unicode_normalize(:nfd).gsub(/\p{Mn}/, "").downcase rx = Regexp.new(rxstr, Regexp::IGNORECASE) tokens << [:test, ConditionForeignRegexp.new(s[1], rx)] rescue RegexpError => e @warnings << "bad regular expression in #{s[0]} - #{e.message}" tokens << [:test, ConditionForeign.new(s[1], s[2])] end elsif s.scan(/(?:t|type)\s*[:=]\s*(?:"(.*?)"|([’'\-\u2212\p{L}\p{Digit}_\*]+))/i) tokens << [:test, ConditionTypes.new(s[1] || s[2])] elsif s.scan(/(?:ft|flavor)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionFlavor.new(s[1] || s[2])] elsif s.scan(/(?:fn)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+|\*))/i) tokens << [:test, ConditionFlavorName.new(s[1] || s[2])] elsif s.scan(/(?:o|oracle)\s*[:=]\s*(?:"(.*?)"|([^\s\)]+))/i) tokens << [:test, ConditionOracle.new(s[1] || s[2])] elsif s.scan(/(?:keyword)\s*[:=]\s*(?:"(.*?)"|([^\s\)]+))/i) tokens << [:test, ConditionKeyword.new(s[1] || s[2])] elsif s.scan(/(?:a|art|artist)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionArtist.new(s[1] || s[2])] elsif s.scan(/(?:rulings)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionRulings.new(s[1] || s[2])] elsif s.scan(/(cn|tw|fr|de|it|jp|kr|pt|ru|sp|cs|ct|foreign)\s*[:=]\s*(?:"(.*?)"|([^\s\)]+))/i) tokens << [:test, ConditionForeign.new(s[1], s[2] || s[3])] elsif s.scan(/any\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionAny.new(s[1] || s[2])] elsif s.scan(/(banned|restricted|legal)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_\-\*]+))/i) klass = Kernel.const_get("Condition#{s[1].capitalize}") tokens << [:test, klass.new(s[2] || s[3])] elsif s.scan(/(?:f|format)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_\-\*]+))/i) tokens << [:test, ConditionFormat.new(s[1] || s[2])] elsif s.scan(/(?:name|n)\s*(>=|>|<=|<|=|:)\s*(?:"(.*?)"|([\p{L}\p{Digit}_\-]+))/i) op = s[1] op = "=" if op == ":" tokens << [:test, ConditionNameComparison.new(op, s[2] || s[3])] elsif s.scan(/(?:e|set|edition)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) sets = [s[1] || s[2]] sets << (s[1] || s[2]) while s.scan(/,(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionEdition.new(*sets)] elsif s.scan(/number\s*(>=|>|<=|<|=|:)\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+|\*))/i) tokens << [:test, ConditionNumber.new(s[2] || s[3], s[1])] elsif s.scan(/(?:w|wm|watermark)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+|\*))/i) tokens << [:test, ConditionWatermark.new(s[1] || s[2])] elsif s.scan(/(?:lore)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+|\*))/i) tokens << [:test, ConditionLore.new(s[1] || s[2])] elsif s.scan(/deck\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_\-]+))/i) tokens << [:test, ConditionDeck.new(s[1] || s[2])] elsif s.scan(/(?:b|block)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) blocks = [s[1] || s[2]] blocks << (s[1] || s[2]) while s.scan(/,(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionBlock.new(*blocks)] elsif s.scan(/st\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionSetType.new(s[1] || s[2])] elsif s.scan(/(c|ci|color|id|ind|identity|indicator)\s*(>=|>|<=|<|=|:)\s*(?:"(\d+)"|(\d+))/i) kind = s[1].downcase kind = "c" if kind == "color" kind = "ind" if kind == "indicator" kind = "ci" if kind == "id" kind = "ci" if kind == "identity" cmp = s[2] cmp = "=" if cmp == ":" color = s[3] || s[4] tokens << [:test, ConditionColorCountExpr.new(kind, cmp, color)] elsif s.scan(/(?:c|color)\s*:\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionColors.new(parse_color(s[1] || s[2]))] elsif s.scan(/(?:ci|id|identity)\s*[:!]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionColorIdentity.new(parse_color(s[1] || s[2]))] elsif s.scan(/(?:ind|indicator)\s*:\s*\*/i) tokens << [:test, ConditionColorIndicatorAny.new] elsif s.scan(/(?:ind|indicator)\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) tokens << [:test, ConditionColorIndicator.new(parse_color(s[1] || s[2]))] elsif s.scan(/(print|firstprint|lastprint)\s*(>=|>|<=|<|=|:)\s*(?:"(.*?)"|([\-[\p{L}\p{Digit}_]+]+))/i) op = s[2] op = "=" if op == ":" klass = Kernel.const_get("Condition#{s[1].capitalize}") tokens << [:test, klass.new(op, s[3] || s[4])] elsif s.scan(/(?:r|rarity)\s*(>=|>|<=|<|=|:)\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) op = s[1] op = "=" if op == ":" rarity = s[2] || s[3] begin tokens << [:test, ConditionRarity.new(op, rarity)] rescue @warnings << "unknown rarity: #{rarity}" end elsif s.scan(/(pow|power|tou|toughness|cmc|loy|loyalty|stab?|stability|year|rulings)\s*(>=|>|<=|<|=|:)\s*(pow\b|power\b|tou\b|toughness\b|cmc\b|loy\b|loyalty\b|stab?\b|stability\b|year\b|rulings\b|[²\d\.\-\*\+½x∞\?]+)/i) aliases = {"power" => "pow", "loyalty" => "loy", "stab" => "sta", "stability" => "sta", "toughness" => "tou"} a = s[1].downcase a = aliases[a] || a op = s[2] op = "=" if op == ":" b = s[3].downcase b = aliases[b] || b tokens << [:test, ConditionExpr.new(a, op, b)] elsif s.scan(/(c|ci|id|ind|color|identity|indicator)\s*(>=|>|<=|<|=|!)\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) kind = s[1].downcase kind = "c" if kind == "color" kind = "ci" if kind == "id" kind = "ci" if kind == "identity" kind = "ind" if kind == "indicator" cmp = s[2] cmp = "=" if cmp == "!" tokens << [:test, ConditionColorExpr.new(kind, cmp, parse_color(s[3] || s[4]))] elsif s.scan(/(?:mana|m)\s*(>=|>|<=|<|=|:|!=)\s*((?:[\dwubrgxyzchmno]|\{.*?\})*)/i) op = s[1] op = "=" if op == ":" mana = s[2] tokens << [:test, ConditionMana.new(op, mana)] elsif s.scan(/(is|not)\s*[:=]\s*(vanilla|spell|permanent|funny|timeshifted|colorshifted|reserved|multipart|promo|primary|secondary|front|back|commander|digital|reprint|fetchland|shockland|dual|fastland|bounceland|gainland|filterland|checkland|manland|creatureland|scryland|battleland|guildgate|karoo|painland|triland|canopyland|shadowland|storageland|tangoland|canland|phyrexian|hybrid|augment|unique|booster|draft|historic|holofoil|foilonly|nonfoilonly|foil|nonfoil|foilboth|brawler|keywordsoup|partner|oversized|spotlight|modal|textless|fullart|full|ante|custom|mainfront|buyabox|tricycleland|triome|racist|errata)\b/i) tokens << [:not] if s[1].downcase == "not" cond = s[2].capitalize cond = "Bounceland" if cond == "Karoo" cond = "Manland" if cond == "Creatureland" cond = "Battleland" if cond == "Tangoland" cond = "Canopyland" if cond == "Canland" cond = "Fullart" if cond == "Full" cond = "Triome" if cond == "Tricycleland" klass = Kernel.const_get("ConditionIs#{cond}") tokens << [:test, klass.new] elsif s.scan(/has:(partner|watermark|indicator)\b/) cond = s[1].capitalize klass = Kernel.const_get("ConditionHas#{cond}") tokens << [:test, klass.new] elsif s.scan(/(is|not|layout)\s*[:=]\s*(normal|leveler|vanguard|dfc|double-faced|transform|token|split|flip|plane|scheme|phenomenon|meld|aftermath|adventure|saga|planar|augment|host)\b/i) tokens << [:not] if s[1].downcase == "not" kind = s[2].downcase kind = "double-faced" if kind == "transform" kind = "double-faced" if kind == "dfc" # mtgjson v3 vs v4 differences kind = "planar" if kind == "plane" kind = "planar" if kind == "phenomenon" tokens << [:test, ConditionLayout.new(kind)] elsif s.scan(/(is|not|game)\s*[:=]\s*(paper|arena|mtgo|xmage)\b/i) tokens << [:not] if s[1].downcase == "not" cond = s[2].capitalize klass = Kernel.const_get("ConditionIs#{cond}") tokens << [:test, klass.new] elsif s.scan(/in\s*[:=]\s*(paper|arena|mtgo|foil|nonfoil|booster|xmage)\b/i) cond = s[1].capitalize klass = Kernel.const_get("ConditionIn#{cond}") tokens << [:test, klass.new] elsif s.scan(/in\s*[:=]\s*(basic|common|uncommon|rare|mythic|special)\b/i) kind = s[1].downcase tokens << [:test, ConditionInRarity.new(kind)] elsif s.scan(/in\s*[:=]\s*(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) # This needs to be last after all other in: sets = [s[1] || s[2]] sets << (s[1] || s[2]) while s.scan(/,(?:"(.*?)"|([\p{L}\p{Digit}_]+))/i) sets = sets.map(&:downcase) # Does it look like a set type? # We have a list # Commented out things are also set codes so they take priority # # It's a bit awkward as both set lists and set types lists are in db # and we don't have access to it here set_types = [ "2hg", # "arc", "archenemy", "booster", "box", # "cmd", # "cns", "commander", "conspiracy", "core", "dd", "deck", "duel deck", "duels", "ex", "expansion", "fixed", # "fnm", # this one doesn't have longer alternative form :-/ "from the vault", "ftv", "funny", "judge gift", "masterpiece", "masters", "me", "memorabilia", "modern", "multiplayer", "pc", "pds", "planechase", "portal", "premium deck", "promo", "spellbook", "st", "standard", "starter", "std", "token", "treasure chest", "two-headed giant", "un", "unset", "vanguard", "wpn", "instore", ] if sets.size == 1 and set_types.include?(sets[0].tr("_", " ")) tokens << [:test, ConditionInSetType.new(sets[0])] else tokens << [:test, ConditionInEdition.new(*sets)] end elsif s.scan(/(is|frame|not)\s*[:=]\s*(compasslanddfc|colorshifted|devoid|extendedart|legendary|miracle|mooneldrazidfc|nyxtouched|originpwdfc|sunmoondfc|tombstone)\b/i) tokens << [:not] if s[1].downcase == "not" tokens << [:test, ConditionFrameEffect.new(s[2].downcase)] elsif s.scan(/(is|frame|not)\s*[:=]\s*(old|new|future|modern|m15)\b/i) tokens << [:not] if s[1].downcase == "not" tokens << [:test, ConditionFrame.new(s[2].downcase)] elsif s.scan(/frame\s*[:=]\s*(?:"(.*?)"|([\.\p{L}\p{Digit}_]+))/i) frame = (s[1]||s[2]).downcase frame_types = %W[old new future modern m15] frame_effects = %W[compasslanddfc colorshifted devoid extendedart legendary miracle mooneldrazidfc nyxtouched originpwdfc sunmoondfc tombstone].sort @warnings << "Unknown frame: #{frame}. Known frame types are: #{frame_types.join(", ")}. Known frame effects are: #{frame_effects.join(", ")}." elsif s.scan(/(is|not)\s*[:=]\s*(black-bordered|silver-bordered|white-bordered)\b/i) tokens << [:not] if s[1].downcase == "not" tokens << [:test, ConditionBorder.new(s[2].sub("-bordered", "").downcase)] elsif s.scan(/(is|not)\s*[:=]\s*borderless\b/i) tokens << [:not] if s[1].downcase == "not" tokens << [:test, ConditionBorder.new("borderless")] elsif s.scan(/border\s*[:=]\s*(black|silver|white|none|borderless)\b/i) kind = s[1].downcase kind = "borderless" if kind == "none" tokens << [:test, ConditionBorder.new(kind)] elsif s.scan(/(?:sort|order)\s*[:=]\s*(?:"(.*?)"|([\-\,\.\p{L}\p{Digit}_]+))/i) # Warning will be generated by sorter tokens << [:metadata, {sort: (s[1]||s[2]).downcase}] elsif s.scan(/(?:view|display)\s*[:=]\s*(?:"(.*?)"|([\.\p{L}\p{Digit}_]+))/i) view = (s[1]||s[2]).downcase known_views = ["checklist", "full", "images", "text"] unless known_views.include?(view) @warnings << "Unknown view: #{view}. Known options are: #{known_views.join(", ")}, and default." end tokens << [:metadata, {view: view}] elsif s.scan(/\+\+/i) tokens << [:metadata, {ungrouped: true}] elsif s.scan(/time\s*[:=]\s*(?:"(.*?)"|([\.\p{L}\p{Digit}_]+))/i) # Parsing is downstream responsibility tokens << [:time, parse_time(s[1] || s[2])] elsif s.scan(/"(.*?)"/i) tokens << [:test, ConditionWord.new(s[1])] elsif s.scan(/other\s*[:=]\s*/i) tokens << [:other] elsif s.scan(/part\s*[:=]\s*/i) tokens << [:part] elsif s.scan(/related\s*[:=]\s*/i) tokens << [:related] elsif s.scan(/alt\s*[:=]\s*/i) tokens << [:alt] elsif s.scan(/not\b/i) tokens << [:not] elsif s.scan(/\*/i) # A quick hack, maybe add ConditionAll ? tokens << [:test, ConditionTypes.new("*")] elsif s.scan(/([^-!<>=:"\s&\/()][^<>=:"\s&\/()]*)(?=$|[\s&\/()])/i) # Veil-Cursed and similar silliness tokens << [:test, ConditionWord.new(s[1].gsub("-", " "))] else # layout:fail, protection: etc. s.scan(/(\S+)/i) @warnings << "Unrecognized token: #{s[1]}" tokens << [:test, ConditionWord.new(s[1])] end end [tokens, @warnings] end private def parse_color(color_text) color_text = color_text.downcase if Color::Names[color_text] Color::Names[color_text] else return color_text if color_text =~ /\A[wubrgcm]+\z/ fixed = color_text.gsub(/[^wubrgcm]/, "") @warnings << "Unrecognized color query: #{color_text.inspect}, correcting to #{fixed.inspect}" fixed end end def parse_time(time) time = time.downcase case time when /\A\d{4}\z/ # It would probably be easier if we had end-of-period semantics, but we'd need to hack Date.parse for it # It parses "March 2010" as "2010.3.1" Date.parse("#{time}.1.1") when /\A\d{4}\.\d{1,2}\z/ Date.parse("#{time}.1") when /\d{4}/ # throw at Date.parse but only if not set name / symbol begin Date.parse(time) rescue time end else time end end end
$LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'jekyll-haml-markup' require 'minitest/autorun' def root_dir(*subdirs) File.expand_path(File.join('..', *subdirs), __dir__) end def test_dir(*subdirs) root_dir('test', *subdirs) end def source_dir(*subdirs) test_dir('fixtures', *subdirs) end def dest_dir(*subdirs) test_dir('.tmp', *subdirs) end def default_configuration Marshal.load(Marshal.dump(Jekyll::Configuration::DEFAULTS)) end def build_configs(overrides, base_hash = default_configuration) Jekyll::Utils.deep_merge_hashes(base_hash, overrides) end def site_configuration(overrides = {}) configs = build_configs 'destination' => dest_dir, 'incremental' => false build_configs overrides, configs end def fixture_site(overrides = {}) Jekyll::Site.new(site_configuration(overrides)) end def xslt Nokogiri::XSLT <<-XSL <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="UTF-8" indent="yes"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <xsl:copy-of select="."> </xsl:template> </xsl:stylesheet> XSL end
module Rockauth module Controllers::UnsafeParameters class UnsafeParametersError < ActionController::BadRequest; end extend ActiveSupport::Concern included do before_filter :reject_unsafe_parameters! rescue_from UnsafeParametersError do render_error 400, I18n.t("rockauth.errors.unsafe_parameters_error") end end def detect_unsafe_parameters hash=request.GET if hash.is_a? Hash return hash.any? do |key, value| return true if Rockauth::Configuration.unsafe_url_parameters.map(&:to_s).include? key.to_s return true if detect_unsafe_parameters value end elsif hash.is_a? Array return hash.any? do |item| detect_unsafe_parameters item end else return false end end def reject_unsafe_parameters! return true if Rockauth::Configuration.unsafe_url_parameters.empty? if detect_unsafe_parameters fail UnsafeParametersError, I18n.t("rockauth.errors.unsafe_parameters_error") end true end end end
json.array!(@finance_plans) do |finance_plan| json.extract! finance_plan, :id, :description json.url finance_plan_url(finance_plan, format: :json) end
module SportsDataApi module Mlb class Players include Enumerable ## # Initialize by passing the raw XML returned from the API def initialize(xml) @players = [] xml = xml.first if xml.is_a? Nokogiri::XML::NodeSet if xml.is_a? Nokogiri::XML::Element xml.xpath('team').each do |team| team.xpath('players').xpath('player').each do |player| p = Player.new(player, team['id']) @players << p end end end @players end def [](search_index) found_index = @teams.index(search_index) unless found_index.nil? @teams[found_index] end end ## # Make the class Enumerable def each(&block) @players.each do |player| if block_given? block.call player else yield player end end end end end end
class HarmonicOscilatorParticle attr_accessor :r, :v, :f, :m, :a, :r1, :r2, :r3, :r4, :r5 M = 70.0 K = 10000.0 GAMMA = 100.0 R_D = 1 V_D = - GAMMA / M / 2 def initialize(r = R_D, v = V_D) @r = r @v = v @m = M @f = - (K * r + GAMMA * v) @a = @f / @m init_r end def init_r @r1 = @v @r2 = @a @r3 = (- K * @r1 - GAMMA * @r2) / @m @r4 = (- K * @r2 - GAMMA * @r3) / @m @r5 = (- K * @r3 - GAMMA * @r4) / @m end def exact_r(t) Math::E ** (- (GAMMA / (2 * @m) * t)) * Math.cos(Math.sqrt(K / @m - GAMMA ** 2 / (4 * @m ** 2)) * t) end end
require "spec_helper" describe ParentsController do describe "routing" do it "routes to #index" do get("/parents").should route_to("parents#index") end it "routes to #new" do get("/parents/new").should route_to("parents#new") end it "routes to #show" do get("/parents/1").should route_to("parents#show", :id => "1") end it "routes to #edit" do get("/parents/1/edit").should route_to("parents#edit", :id => "1") end it "routes to #create" do post("/parents").should route_to("parents#create") end it "routes to #update" do put("/parents/1").should route_to("parents#update", :id => "1") end it "routes to #destroy" do delete("/parents/1").should route_to("parents#destroy", :id => "1") end end end
class AddLogoToUsers < ActiveRecord::Migration def self.up add_column :users, :logo, :text add_column :users, :organization, :boolean, :default => false end def self.down remove_column :users, :organization remove_column :users, :logo end end
class CreateSeos < ActiveRecord::Migration[5.2] def change create_table :seos do |t| t.integer :position t.datetime :deleted_at t.timestamps end add_index :seos, :deleted_at end end
Gem::Specification.new do |s| s.platform = Gem::Platform::RUBY s.name = 'spree_pos' s.version = '1.1' s.summary = 'Point of sale screen for Spree' s.required_ruby_version = '>= 1.8.7' s.author = 'Torsten R' s.email = 'torsten@villataika.fi' s.files = Dir['CHANGELOG', 'README.md', 'LICENSE', 'lib/**/*', 'app/**/*'] s.require_path = 'lib' s.requirements << 'none' s.add_dependency('spree_core', '>= 1.2') s.add_dependency('barby') s.add_dependency('prawn') s.add_dependency('rqrcode') # missing dependency in barby s.add_dependency('chunky_png') end
$:.unshift(File.expand_path('./lib', ENV['rvm_path'])) # Add RVM's lib directory to the load path. require "bundler/capistrano" require "rvm/capistrano" # Load RVM's capistrano plugin. set :rvm_type, :user set :application, "masasx" set :domain, "ci.masas-sics.ca" set :repository, "git://github.com/jevy/masasx.git" set :use_sudo, false set :deploy_to, "/var/www/masasx" set :scm, :git set :user, "rails" role :app, domain role :web, domain role :db, domain, :primary => true set :normalize_asset_timestamps, false namespace :deploy do task :start, :roles => :app do run "touch #{current_release}/tmp/restart.txt" end desc "Restart Application" task :restart, :roles => :app do run "touch #{current_release}/tmp/restart.txt" end desc "Copy the database file" task :database_file, :roles => :app do run "cp #{shared_path}/secret/database.yml #{current_release}/config/" end end before "deploy:finalize_update", "deploy:database_file" require './config/boot' require 'airbrake/capistrano'
class AdminFriendsPercentageWorker < BaseWorker def self.category; :admin end def self.metric; :friends_percentage end def perform perform_with_tracking do AdminMetrics.new.fetch_friend_metrics! end end statsd_measure :perform, metric_prefix end
class SessionControllerController < ApplicationController def show end private def user_params params.require(:users).permit(:email,:password) end def new # sign in form end def create # attempt login, from form user = User.find_by_credentials(params[:user][:email], params[:user][:password]) if user user.reset_session_token session[:session_token] = user.session_token render "User Logged IN" else render "Wrong password" end end def destory if logged_in? log_in_user!(current_user) end render "user logged out" end end
=begin input: non empty string output: return the middle character or characters data: array, string algorithm: split the array into characters (including space) divide size by 2 if its remainder is 1 return middle number if remainder is 0 return middle and middle + 1 =end def center_of(string) array = string.chars middle = array.size / 2 if array.size % 2 == 0 array[middle - 1] + array[middle] else array[middle] end end p center_of('I love ruby') == 'e' p center_of('Launch School') == ' ' p center_of('Launch') == 'un' p center_of('Launchschool') == 'hs' p center_of('x') == 'x'
class GoalsController < ApplicationController def new @resolution = Resolution.find(params[:resolution_id]) @goal = Goal.new end def create goal = resolution.goals.where(goal_params).first_or_create if goal.save flash[:notice] = "Goal created for #{resolution.title}" redirect_to dashboard_path else flash[:notice] = "Please try again" redirect_to dashboard_path end end def edit @resolution = Resolution.find(params[:resolution_id]) @goal = Goal.find(params[:id]) end def update goal = Goal.find(params[:id]) if goal.update(goal_params) flash[:notice] = "Goal Updated Successfully" redirect_to dashboard_path else flash[:notice] = "Please try again" redirect_to dashboard_path end end def destroy resolution.goals.find(params[:id]).destroy flash[:notice] = "Goal removed" redirect_to dashboard_path end def goal_complete goal = resolution.goals.find(params[:id]) goal.update(completed: true) flash[:notice] = "Congratulations on reaching your goal!" redirect_to dashboard_path end private def resolution @resolution ||= Resolution.find(params[:resolution_id]) end def goal_params params.require(:goal).permit(:resolution_id, :name, :completed) end end
require 'spec_helper' describe User do it "processes omniauth from existing user" do auth = { :provider => "twitter", :uid => "1234567", :info => { :nickname => "hafizbadrie" } } user = FactoryGirl.create(:user) tested_user = User.process_omniauth(auth) expect(tested_user).to eq(user) end it "processes omniauth with new user" do auth = { :provider => "twitter", :uid => "1234567", :info => { :nickname => "hafizbadrie" } } tested_user = User.process_omniauth(auth) expect(tested_user.persisted?).to be_false end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) ChannelDetail.create([{ rank: 1, channel: "SimpleKey", channel_title: "Kripperion", views: 1203301, subscribers_total: 123445, subscriber_loss: 987, likes: 45603, dislikes: 2345, }, { rank: 2, channel: "AnotherKey", channel_title: "Vsauce", views: 2889998, subscribers_total: 456623, subscriber_loss: 12344, likes: 234551, dislikes: 33456, } ])
users = [ { name: 'Fahad', orders: [ { description: 'a bike' } ] }, { name: 'Abdulrahman', orders: [ { description: 'bees' }, { description: 'fishing rod' } ] }, { name: 'Muhannad', orders: [ { description: 'a MacBook' }, { description: 'The West Wing DVDs' }, { description: 'headphones' }, { description: 'a kitten' } ] } ] first_order_for_each_user = users.map do |user| user[:orders].first end puts first_order_for_each_user
SIZE = 2 class Candidate attr_accessor :ractor def initialize @ractor = Ractor.new do value = Ractor.receive loop { Ractor.yield value } end end end class Group attr_reader :candidate_ractors, :candidates def initialize(candidates) @candidates = candidates @candidate_ractors = candidates.map { _1[:ractor] } Ractor.new candidate_ractors do |candidate_ractors| value = false (SIZE ** 2 - 1).times do r, value = Ractor.select(*candidate_ractors) candidate_ractors.delete r break if value end candidate_ractors.each { _1.send !value } Ractor.yield true end end end class Board attr_accessor :board, :groups def initialize @board = SIZE.times.map do |row| SIZE.times.map do |col| SIZE.times.map do |cell_row| SIZE.times.map do |cell_col| (SIZE ** 2).times.map do |value| { row: row, col: col, cell_row: cell_row, cell_col: cell_col, value: value, ractor: Candidate.new.ractor } end end.flatten end.flatten end.flatten end.flatten end def make_groups rows = board.group_by do |candidate| (candidate[:row] * SIZE + candidate[:cell_row]) end.values.map do |row| row.group_by do |candidate| candidate[:value] end end.map(&:values).flatten(1) cols = board.group_by do |candidate| (candidate[:col] * SIZE + candidate[:cell_col]) end.values.map do |row| row.group_by do |candidate| candidate[:value] end end.map(&:values).flatten(1) cells = board.group_by do |candidate| (candidate[:row] * SIZE + candidate[:col]) end.values.map do |row| row.group_by do |candidate| candidate[:value] end end.map(&:values).flatten(1) # Only one not by value squares = board.group_by do |candidate| (candidate[:row] * SIZE + candidate[:col]) end.values.map do |row| row.group_by do |candidate| (candidate[:cell_row] * SIZE + candidate[:cell_col]) end end.map(&:values).flatten(1) @groups = (rows + cols + cells + squares).map do |group| # @groups = (cols).map do |group| # Group.new(group.map { _1[:ractor] }) Group.new(group) end end def send(row, col, cell_row, cell_col, value) value = 0 if value == SIZE ** 2 find(row, col, cell_row, cell_col, value)[:ractor].send true end def find(row, col, cell_row, cell_col, value) board.select do |square| square[:row] == row && square[:col] == col && square[:cell_row] == cell_row && square[:cell_col] == cell_col && square[:value] == value end.first end def print_solution puts board.select { _1[:ractor].take }. sort_by { [_1[:row], _1[:cell_row], _1[:col], _1[:cell_col]] }. map { _1[:value] }. each_slice(4).to_a. map { _1.join(" ").gsub("0", (SIZE ** 2).to_s) }.join("\n") end end board = Board.new board.send(0,1,0,1,3) board.send(0,1,1,1,2) board.send(1,0,0,0,3) board.send(1,0,1,0,4) puts Ractor.count board.make_groups puts Ractor.count board.print_solution b2 = Board.new b2.send(1,0,0,0,4) b2.send(1,0,1,1,2) b2.send(0,1,1,0,1) b2.send(1,1,1,1,3) b2.make_groups puts Ractor.count b2.print_solution ###
require 'rails_helper' RSpec.feature 'Admin signs in' do scenario 'they are redirected to admin dashboard' do user = create(:user, admin: true) visit root_path find('#username-sign-in').set(user.username) find('#password-sign-in').set(user.password) click_button 'Submit' expect(current_path).to eq(admin_root_path) end end
module Api module V1 class GalleriesController < Api::V1::BaseController def show @gallery = Gallery.find(params[:id]) if @gallery.user == current_user || current_user.admin? render json: @gallery else render json: { message: "Access denied. You are not authorized to enter" } end end def new @gallery = current_user.galleries.build end def create @gallery = Gallery.new(gallery_params) if @gallery.save render json: @gallery, status: 201 else render json: @gallery.errors, status: :unprocessable_entity end end private def gallery_params ActiveModelSerializers::Deserialization.jsonapi_parse(params) end end end end
# frozen_string_literal: true require "resque" module Sentry module Resque def perform if Sentry.initialized? SentryReporter.record(queue, worker, payload) do super end else super end end class SentryReporter class << self def record(queue, worker, payload, &block) Sentry.with_scope do |scope| begin contexts = generate_contexts(queue, worker, payload) scope.set_contexts(**contexts) scope.set_tags("resque.queue" => queue) name = contexts.dig(:"Active-Job", :job_class) || contexts.dig(:"Resque", :job_class) scope.set_transaction_name(name, source: :task) transaction = Sentry.start_transaction(name: scope.transaction_name, source: scope.transaction_source, op: "queue.resque") scope.set_span(transaction) if transaction yield finish_transaction(transaction, 200) rescue Exception => exception ::Sentry::Resque.capture_exception(exception, hint: { background: false }) finish_transaction(transaction, 500) raise end end end def generate_contexts(queue, worker, payload) context = {} if payload["class"] == "ActiveJob::QueueAdapters::ResqueAdapter::JobWrapper" active_job_payload = payload["args"].first context[:"Active-Job"] = { job_class: active_job_payload["job_class"], job_id: active_job_payload["job_id"], arguments: active_job_payload["arguments"], executions: active_job_payload["executions"], exception_executions: active_job_payload["exception_executions"], locale: active_job_payload["locale"], enqueued_at: active_job_payload["enqueued_at"], queue: queue, worker: worker.to_s } else context[:"Resque"] = { job_class: payload["class"], arguments: payload["args"], queue: queue, worker: worker.to_s } end context end def finish_transaction(transaction, status) return unless transaction transaction.set_http_status(status) transaction.finish end end end end end Resque::Job.send(:prepend, Sentry::Resque)
class StaticPagesController < ApplicationController # This action uses the signed_in? method from sessions_helper # to see if the user is signed in. # Called when a user navigates to root def home if signed_in? redirect_to room_rooms_path(current_user.username) end # These are variables available to our views # Within application.html.erb, there's a statement that # checks to see if these values are set. @landing_page_view = true @skip_header = true @skip_footer = true end def help end def about @skip_container = true @skip_header = false @skip_footer = false end end
class AuthorSerializer < ActiveModel::Serializer attributes :username, :email end
class Competition < ApplicationRecord validates :name, :phone, :email, :presence => true end
# simple UDP logger require 'logstasher/device' require 'socket' module LogStasher module Device class UDP include ::LogStasher::Device attr_reader :options, :socket def initialize(options = {}) @options = default_options.merge(stringify_keys(options)) @socket = UDPSocket.new end def close @socket.close end def write(log) @socket.send(log, 0, options['hostname'], options['port']) end private def default_options { 'hostname' => '127.0.0.1', 'port' => 31459, } end end end end
module TeamUserMutations MUTATION_TARGET = 'team_user'.freeze PARENTS = ['user','team'].freeze module SharedCreateAndUpdateFields extend ActiveSupport::Concern included do argument :role, GraphQL::Types::String, required: false end end class Create < Mutations::CreateMutation include SharedCreateAndUpdateFields argument :user_id, GraphQL::Types::Int, required: true, camelize: false argument :team_id, GraphQL::Types::Int, required: true, camelize: false argument :status, GraphQL::Types::String, required: true end class Update < Mutations::UpdateMutation include SharedCreateAndUpdateFields argument :user_id, GraphQL::Types::Int, required: false, camelize: false argument :team_id, GraphQL::Types::Int, required: false, camelize: false argument :status, GraphQL::Types::String, required: false end class Destroy < Mutations::DestroyMutation; end end
class Mechanic < ApplicationRecord validates_presence_of :name, :years_experience has_many :mechanic_rides has_many :rides, through: :mechanic_rides def self.average_experience average(:years_experience) end def open_rides rides.where(open: true).order('thrill_rating DESC') end def add_ride(params) new_ride = Ride.find(params) rides.push(new_ride) end end
class MealPlan < ApplicationRecord belongs_to :user has_many :meals, inverse_of: :meal_plan, dependent: :destroy validates :start_date, presence: true validates :end_date, presence: true validates :user, presence: true accepts_nested_attributes_for :meals def build_meals user_recipe_ids = user.recipes.pluck(:id) #returning array of recipe ids (start_date..end_date).each do |date| unused_recipe_ids = user_recipe_ids - meals.map(&:recipe_id) if unused_recipe_ids.empty? available_recipe_ids = user_recipe_ids else available_recipe_ids = unused_recipe_ids end meals.build(date: date, recipe_id: available_recipe_ids.sample) end end def to_s "#{start_date} - #{end_date}" end end
class Favorite < ApplicationRecord belongs_to :user belongs_to :cook validates_uniqueness_of :cook_id, scope: :user_id end
# frozen_string_literal: true # == Schema Information # # Table name: tasks # # id :integer not null, primary key # name :string # completed :boolean # created_at :datetime not null # updated_at :datetime not null # class Task < ActiveRecord::Base validates :name, :list_id, presence: true validates :completed, inclusion: { in: [true, false] } belongs_to :list, class_name: :List, foreign_key: :list_id, primary_key: :id has_one :author, through: :list, source: :list end
# frozen_string_literal: true require 'rspec' require './roman_to_int' describe RomanToInt do let(:roman_number) do { "I": 1, "V": 5, "X": 10, "C": 100, "L": 50, "D": 500, "M": 1000 } end context 'Convert the RomanToInt response' do describe 'Call Covert method integer' do it 'It should conver I to 1' do expect(RomanToInt.convert('I')).to eq(1) end it 'It should conver II to 2' do expect(RomanToInt.convert('II')).to eq(2) end it 'It should conver III to 3' do expect(RomanToInt.convert('III')).to eq(3) end # it 'it should Convert II to 2' do # end end end end
require 'spec_helper' describe "groups/show.html.erb" do before(:each) do pwd = 'cloud$' @user = User.create! :first_name => 'Dale', :last_name => 'Olds', :display_name => 'Dale O.', :password => pwd, :confirm_password => pwd, :email => 'olds@vmware.com' sign_in @user @org = assign(:org, stub_model(Org, :display_name => "An org", :id => 1 )) @group = assign(:group, stub_model(Group, :display_name => "Group", :org => @org )) end it "renders attributes in <p>" do render # Run the generator again with the --webrat flag if you want to use webrat matchers #rendered.should match(/Group/) end end
class AclController < ApplicationController def acl render json: User.current_user.tocat_role.try(:permissions).to_json end end
require 'app/models/social_media_account' require 'app/presenters/paginated_presenter' class SocialMediaAccountPresenter < Jsonite properties :website, :handle link(:external) { url } end class SocialMediaAccountsPresenter < PaginatedPresenter property(:social_media_accounts, with: SocialMediaAccountPresenter) { to_a } end
class HomeController < ApplicationController def index @conference = Builderscon::Conference.current end end
class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable # Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :provider, :uid, :oauth_token has_many :course_subscriptions has_many :courses, through: :course_subscriptions has_many :attempts def self.find_for_auth(auth, signed_in_resource=nil) user = User.where(email: auth.info.email).first if !user user = User.create(provider:auth.provider, uid:auth.uid, email: auth.info.email, password: Devise.friendly_token[0,20], oauth_token: auth.credentials.token) #profile = Profile.new(first_name: auth.info.first_name, # last_name: auth.info.last_name, # image: auth.info.image) #profile.user = user #profile.save else user.update_attribute(:oauth_token, auth.credentials.token) #user.profile.update_attributes({ # image: auth.info.image, #}) end user end def self.find_for_facebook_auth(auth, signed_in_resource=nil) user = User.find_for_auth(auth, signed_in_resource) #user.import_facebook_friends return user end def self.find_for_google_oauth2(auth, signed_in_resource=nil) User.find_for_auth(auth, signed_in_resource) end def attempt_count(assignment_id) return self.attempts.where(assignment_id: assignment_id).count end end
class OpenSource::CLI def call #greets user puts "" puts "Welcome to our Facebook Open Source Projects CLI!" menu end def menu #scrape categories and list them puts " " list_categories #select category puts "Please select a category (#) you would like to see projects of or type 'exit' at any point to exit program." #ask for input, scrape projects, and list them get_category_input #ask for input, list project details puts "Please select a project (#) you would like to see details of or type 'exit' at any point to exit program. " get_project_input #Go again or exit puts "Would you like to see another project? (Y/N)" get_menu_input end def list_categories #scrape categories from website OpenSource::Scraper.scrape_categories if OpenSource::Category.all.empty? puts "Open Source Project Categories: ".green puts "" OpenSource::Category.all.each_with_index {|category, index| puts "#{index+1}. #{category.name}".blue} puts "" end def list_projects(category) # scrape project from category from website OpenSource::Scraper.scrape_projects(category) puts "" puts "#{titleize(category.name)} Projects: ".green puts "" OpenSource::Project.all.each_with_index {|project, index| puts "#{index + 1}. #{project.name}".blue} puts "" end def get_project_detail(project) puts "" puts "#{project.name.green}" puts "" puts " Category: ".blue + "#{project.category.name}".red puts "" puts " Description: ".blue + "#{project.description}".red puts "" puts " GitHub: ".blue + "#{project.github}".red puts "" puts " Website: ".blue + "#{project.website}".red puts "" end def get_category_input input = gets.strip index = input.to_i - 1 #if valid input, select category and projects from that category if index.between?(0, OpenSource::Category.all.length-1) category = OpenSource::Category.all[index] list_projects(category) elsif input.downcase == "exit" exit_program else puts "Sorry, I didn't understand that command" get_category_input end end def get_project_input input = gets.strip index = input.to_i - 1 #if valid input, select project and its details if index.between?(0,OpenSource::Project.all.length-1) project = OpenSource::Project.all[index] get_project_detail(project) elsif input.downcase == "exit" exit_program else puts "Sorry, I didn't understand that command" get_project_input end end #repeat program or exit def get_menu_input input = gets.strip if input == "Y" menu elsif input == "N" || input.downcase == "exit" exit_program else puts "Sorry, I only understand 'Y' or 'N'" get_menu_input end end def titleize(string) titleized = string.split.each {|char| char.capitalize!} titleized = titleized.join(' ') titleized end def exit_program puts "" puts "Thank you for exploring Facebook's Open Source Projects! Have a nice day :)" puts "" exit end end
describe Bothan::App do context 'Dashboards' do before(:each) do basic_authorize ENV['METRICS_API_USERNAME'], ENV['METRICS_API_PASSWORD'] end let(:dashboard_hash) { { dashboard: { name: 'My Awesome Dashboard', slug: 'my-awesome-dashboard', rows: 2, columns: 2, metrics: { '0': { name: 'my-first-metric', boxcolour: '#000', textcolour: '#fff', visualisation: 'number' }, '1': { name: 'my-second-metric', boxcolour: '#fff', textcolour: '#000', visualisation: 'number' }, '2': { name: 'my-third-metric', boxcolour: '#111', textcolour: '#222', visualisation: 'number' }, '3': { name: 'my-fourth-metric', boxcolour: '#ccc', textcolour: '#ddd', visualisation: 'number' } } } } } it 'creates a dashboard' do post '/dashboards', dashboard_hash follow_redirect! expect(last_request.url).to eq('http://example.org/dashboards/my-awesome-dashboard') dashboard = Dashboard.first expect(Dashboard.all.count).to eq(1) expect(dashboard.name).to eq('My Awesome Dashboard') expect(dashboard.slug).to eq('my-awesome-dashboard') expect(dashboard.rows).to eq(2) expect(dashboard.columns).to eq(2) expect(dashboard.metrics.count).to eq(4) expect(dashboard.metrics.first).to eq({ "name" => "my-first-metric", "boxcolour" => "#000", "textcolour" => "#fff", "visualisation" => "number" }) end it 'does not specify a visualisation if default is set' do dashboard_hash[:dashboard][:metrics][:'0'][:visualisation] = 'default' post '/dashboards', dashboard_hash dashboard = Dashboard.first expect(dashboard.metrics.first).to eq({ "name" => "my-first-metric", "boxcolour" => "#000", "textcolour" => "#fff", }) end context 'returns an error' do it 'if the slug is invalid' do dashboard_hash[:dashboard][:slug] = 'This Is TOTALLY NOT A SLUG $%£@$@$@£' post '/dashboards', dashboard_hash expect(last_request.url).to eq('http://example.org/dashboards') expect(last_response.body).to match(/The slug 'This Is TOTALLY NOT A SLUG \$\%\£\@\$\@\$\@\£' is invalid/) end it 'if the slug is duplicated' do Metric.create(name: "dashboard-0") Dashboard.create(name: 'Original', slug: 'my-awesome-dashboard', rows: 1, columns: 1, metrics: "dashboard-0") post '/dashboards', dashboard_hash expect(last_request.url).to eq('http://example.org/dashboards') expect(last_response.body).to match(/The slug 'my-awesome-dashboard' is already taken/) end [:name, :slug, :rows, :columns].each do |col| it "when #{col} is missing" do dashboard_hash[:dashboard].delete(col) post '/dashboards', dashboard_hash expect(last_request.url).to eq('http://example.org/dashboards') expect(last_response.body).to match(/The field #{col} can't be blank/) end end end it 'edits a dashboard' do Metric.create(name: "dashboard-0") dashboard = Dashboard.create(name: 'Original', slug: 'my-awesome-dashboard', rows: 1, columns: 1, metrics: "dashboard-0") put "/dashboards/#{dashboard.slug}", { dashboard: { name: 'My Awesome Dashboard', metrics: { '1': { name: 'my-first-metric', boxcolour: '#000', textcolour: '#fff', visualisation: 'number' } } } } dashboard = Dashboard.last expect(dashboard.name).to eq('My Awesome Dashboard') expect(dashboard.metrics.count).to eq(1) end end end
# Simple Role Syntax # ================== # Supports bulk-adding hosts to roles, the primary server in each group # is considered to be the first unless any hosts have the primary # property set. Don't declare `role :all`, it's a meta role. SERVER_IP = '178.62.61.203' USERNAME = 'deploy' role :app, ["#{USERNAME}@#{SERVER_IP}"] role :web, ["#{USERNAME}@#{SERVER_IP}"] role :db, ["#{USERNAME}@#{SERVER_IP}"] # Extended Server Syntax # ====================== # This can be used to drop a more detailed server definition into the # server list. The second argument is a, or duck-types, Hash and is # used to set extended properties on the server. set :environment, 'production' set :stage, 'production' server SERVER_IP, user: USERNAME, roles: %w{web app db}, my_property: :my_value
# frozen_string_literal: true Sequel.migration do change do create_table(:teams) do primary_key :id column :name, :text column :created_at, 'timestamp with time zone' column :updated_at, 'timestamp with time zone' end end end
class DictionarySearcher attr_reader :dict def initialize(dict) <<<<<<< HEAD @dict = dict end def search(type, term) case type when 1 exact(term) when 2 partial(term) when 3 begins_with(term) when 4 ends_with(term) end end def exact(term) @matches = [] @dict.each { |word| @matches << word if /^#{term}$/ =~ word } end def partial(term) @matches = [] @dict.each { |word| @matches << word if /.*#{term}.*/ =~ word } end def begins_with(term) @matches = [] @dict.each { |word| @matches << word if /^#{term}/ =~ word } end def ends_with(term) @matches = [] @dict.each { |word| @matches << word if /#{term}$/ =~ word } end def show_results puts "Found #{@matches.length} matches:" @matches.each { |word| puts word } ======= @dict end def search # TODO: add case to determine which search method to run end def exact(term) matches = [] # TODO: add regex end def partial(term) matches = [] # TODO: add regex end def begins_with(term) matches = [] # TODO: add regex end def ends_with(term) matches = [] # TODO: add regex end def show_results # TODO: display search results >>>>>>> 02c57034b7dd04c1d19ef45d5890d0bec73fd14a end end
# typed: false require "spec_helper" describe Vndb::Client do describe ".new" do it "can be created" do login_string = "login {\"protocol\":1,\"client\":\"vndb-ruby\",\"clientver\":\"0.1.0\"}\u0004" command_mock = Minitest::Mock.new command_mock.expect(:to_s, login_string) command_spy = Spy.on(Vndb::Command, :new).and_return(command_mock) socket_mock = Minitest::Mock.new socket_mock.expect(:puts, nil, [login_string]) socket_mock.expect(:read, "ok\x04", [1024]) socket_mock.expect(:is_a?, "ok\x04", [IO]) socket_spy = Spy.on(TCPSocket, :open).and_return(socket_mock) response_mock = Minitest::Mock.new response_mock.expect(:success?, true) response_spy = Spy.on(Vndb::Response, :new).and_return(response_mock) Vndb::Client.new assert command_spy.has_been_called? assert socket_spy.has_been_called? assert response_spy.has_been_called? command_mock.verify socket_mock.verify response_mock.verify end end describe ".dbstats" do it "returns database statistics" do dbstats_string = "dbstats\x04" client_mock = Minitest::Mock.new client_mock.expect(:dbstats, dbstats_string) client_spy = Spy.on(Vndb::Client, :new).and_return(client_mock) Vndb::Client.new.dbstats client_spy.has_been_called? client_mock.verify end end end
require 'benchmark' n = 10_000 m = 1.upto(1000).inject({}) { |m, i| m[i] = i; m } Benchmark.benchmark do |bm| puts "#{n} times - ruby #{RUBY_VERSION}" puts puts "each_value" 3.times do bm.report do n.times do m.each_value {} end end end puts puts "values.each" 3.times do bm.report do n.times do m.values.each {} end end end end # $ ruby benchmarks/values_each_v_each_value.rb # 10000 times - ruby 1.9.3 # # each_value # 0.720000 0.000000 0.720000 ( 0.720237) # 0.720000 0.000000 0.720000 ( 0.724956) # 0.730000 0.000000 0.730000 ( 0.730352) # # values.each # 0.910000 0.000000 0.910000 ( 0.917496) # 0.910000 0.010000 0.920000 ( 0.909319) # 0.910000 0.000000 0.910000 ( 0.911225) # $ ruby benchmarks/values_each_v_each_value.rb # 10000 times - ruby 2.0.0 # # each_value # 0.730000 0.000000 0.730000 ( 0.738443) # 0.720000 0.000000 0.720000 ( 0.720183) # 0.720000 0.000000 0.720000 ( 0.720866) # # values.each # 0.940000 0.000000 0.940000 ( 0.942597) # 0.960000 0.010000 0.970000 ( 0.959248) # 0.960000 0.000000 0.960000 ( 0.959099)
class ElasticsearchWorker < BaseWorker def self.category; :elasticsearch end def self.metric; :index end def perform(operation, class_name, id, update_attrs = {}) perform_with_tracking(operation, class_name, id, update_attrs) do model = class_name.constantize object = model.respond_to?(:find) ? model.find(id) : model.new(id: id) case operation when 'index', 'delete' ES.send(operation + '!', object) when 'update_attributes' ES.update_attributes!(object, update_attrs) end true end end statsd_measure :perform, metric_prefix end
class PageViewsController < ApplicationController before_action :set_page_views, only: :index before_action :set_page_view, only: [:show, :update, :destroy] before_action :set_session def index respond_with(@page_views) end def show respond_with(@page_view) end def create @page_view = PageView.new(page_view_params) @page_view.save respond_with(@page_view) end def update @page_view.update(page_view_params) respond_with(@page_view) end def destroy @page_view.destroy respond_with(@page_view) end private def page_views @session ? @session.page_views : PageView end def set_page_views @page_views = PageView.where(page_view_params).order(sort_by).page(params[:page]) end def set_page_view @page_view = PageView.find(params[:id]) end def page_view_params params.permit(:url, :referrer_url, :session_id) end def set_session @session = Session.find(params[:session_id]) if params[:session_id] end end
# encoding: utf-8 describe JmesPath do let :jmespath do described_class.new end describe '#compile' do it 'compiles an expression' do expression = jmespath.compile('foo.bar') expect(expression).to_not be_nil end context 'when there is a syntax error' do it 'raises an error' do expect { jmespath.compile('%') }.to raise_error(JmesPath::ParseError) end end context 'when the expression refers to a function that does not exist' do it 'raises an error' do expect { jmespath.compile('%') }.to raise_error(JmesPath::ParseError) end end context 'when the expression uses an invalid value' do it 'raises an error' do expect { jmespath.compile('%') }.to raise_error(JmesPath::ParseError) end end end end describe JmesPath::Expression do let :expression do JmesPath.new.compile(expression_str) end let :expression_str do 'foo.bar' end describe '#search' do let :input do {'foo' => {'bar' => 42}} end it 'searches the given input and returns the result' do expect(expression.search(input)).to eq(42) end context 'when a function is given the wrong number of arguments' do let :expression_str do 'to_number(foo, bar)' end it 'raises an error' do expect { expression.search(input) }.to raise_error(JmesPath::ArityError) end end context 'when a function is given the wrong kind of argument' do let :expression_str do 'max(@)' end it 'raises an error' do expect { expression.search(input) }.to raise_error(JmesPath::ArgumentTypeError) end end end end
require 'spec_helper' describe Tapbot do it 'has a version number' do expect(Tapbot::VERSION).not_to be nil end describe "CLIENT" do it "should be a Tapbot::Client" do expect(Tapbot.client).to be_a Tapbot::Client end end describe "BASE URI" do it "should return the default base uri" do expect(Tapbot::Configuration::BASE_URI).to eq("https://api.tapbot.com/v1") end end describe "API VERSION" do it "should return the default API version" do expect(Tapbot::Configuration::API_VERSION).to eq("v1") end end describe "User Agent" do it "should return the default API version" do expect(Tapbot::Configuration::USER_AGENT).to eq("tapbot-ruby #{Tapbot::VERSION}") end end describe "Configuration" do Tapbot::Configuration::VALID_OPTIONS_KEYS.each do |key| it "should set the #{key}" do Tapbot.configure do |config| config.send("#{key}=", key) expect(Tapbot.send(key)).to eq(key) end end end end end
class AddIsAdminToUser < ActiveRecord::Migration def change add_column :users, :is_admin, :boolean, default: false User.create!(email: 'admin@gmail.com', password: '12345678',password_confirmation: '12345678', is_admin: true) end end
# frozen_string_literal: true class Ingredient < ApplicationRecord has_many :measured_ingredients has_many :dishes, through: :measured_ingredients validates :name, presence: true end
class Game def initialize @hero = Hero.new initialize_dungeon() end def hero @hero end def dungeon @dungeon end def dungeon_cleared? cleared = true @dungeon.each {|level| level.each{|room| cleared = false if not room.cleared? } } cleared end def exits(show=true) x = @hero.location[0] y = @hero.location[1] exits = [] if x != (@dungeon.length - 1) then if y <= (@dungeon[x+1].length - 1) then exits.push("South") end end exits.push("North") if ((@dungeon[x-1].length-1 >= y) && (x != 0)) exits.push("West") if y != 0 exits.push("East") if y != (@dungeon[x].length - 1) if show then puts "There is an exit to the #{exits[0]}" if exits.length == 1 puts "There are exits to the #{exits[0]} and to the #{exits[1]}" if exits.length == 2 puts "There are exits to the #{exits[0]}, #{exits[1]}, and to the #{exits[2]}" if exits.length == 3 puts "There are exits to the #{exits[0]}, #{exits[1]}, #{exits[3]}, and to the #{exits[2]}" if exits.length == 4 end exits end private def initialize_dungeon @dungeon = [] outer_index = 0 outer_limit = rand(11) while outer_index <= outer_limit row = [] inner_index = 0 inner_limit = rand(11) while inner_index <= inner_limit row.push(Room.new(inner_index)) inner_index += 1 end @dungeon.push(row) outer_index += 1 end end end
module ReportHelper def generate_filepath_and_name(scenario) project_dir = File.expand_path(File.dirname(__FILE__) + '/../../..') $time_fixed ||= Time.now.strftime('%Y-%m-%d_%H-%M-%S') time = Time.now.strftime('%Y-%m-%d_%H-%M-%S') feature_name = scenario.feature.title.underscore_all scenario_title = scenario.title.underscore_all report_folder = File.join("#{project_dir}/build", $time_fixed, feature_name, scenario_title) report_file_name = "#{scenario_title.underscore_all}_#{time}" FileUtils.mkdir_p(report_folder) "#{report_folder}/#{report_file_name}" end def write_html_file(html_file_path) File.write("#{html_file_path}.html", @browser.html) end def take_step_screenshot(screenshot_file_path) @browser.screenshot.save("#{screenshot_file_path}.png") screenshot_file_path end end
class CreateAccessers < ActiveRecord::Migration[5.1] def change create_table :accessers do |t| t.boolean :access_granted t.integer :viewing_id t.integer :viewable_profile t.timestamps end add_index :accessers, :viewing_id add_index :accessers, :viewable_profile end end
class CreateOrders < ActiveRecord::Migration def self.up create_table :orders do |t| t.column :name, :string t.column :street, :string t.column :city, :string t.column :text, :text t.timestamps end end def self.down drop_table :orders end end
require 'rib/test' require 'rib/shell' describe Rib::Shell do paste :rib describe '#loop' do def input str=Rib::Skip mock(shell).get_input{if block_given? then yield else str end} shell.loop ok end would 'exit' do input('exit' ) end would 'also exit' do input(' exit') end would 'ctrl+d' do mock(shell).puts{} ; input(nil) end would ':q' do shell.config[:exit] << ':q'; input(':q') end would '\q' do shell.config[:exit] << '\q'; input('\q') end would 'not puts anything if it is not running' do mock(shell).puts.times(0) shell.eval_binding.eval('self').instance_variable_set(:@shell, shell) input('@shell.stop; throw :rib_exit') end describe 'trap' do before do @token = Class.new(Exception) @old_trap = trap('INT'){ raise @token } mock(shell).handle_interrupt{ mock(shell).get_input{'exit'} } end after do trap('INT', &@old_trap) end def interrupt Process.kill('SIGINT', Process.pid) sleep end would 'fence and restore ctrl+c interruption' do input{ interrupt } expect.raise(@token){ interrupt } end end end describe '#loop_once' do def input str=nil if block_given? mock(shell).get_input{ yield } else mock(shell).get_input{ str } end shell.loop_once ok end would 'handles ctrl+c' do mock(shell).handle_interrupt{} input{ raise Interrupt } end would 'prints result' do mock(shell).puts('=> "mm"'){} input('"m" * 2') end %w[next break].each do |keyword| would "handle #{keyword}" do mock(shell).puts(matching(/^SyntaxError:/)){} input(keyword) end end would 'error in print_result' do mock(Rib).warn(matching(/Error while printing result.*BOOM/m)){} input('obj = Object.new; def obj.inspect; raise "BOOM"; end; obj') end would 'not crash if user input is a blackhole' do mock(Rib).warn(matching(/Error while printing result/)){} input('Rib::Blackhole') end would 'print error from eval' do mock(shell).puts(matching(/RuntimeError/)){} input('raise "blah"') end end describe '#prompt' do would 'be changeable' do shell.config[:prompt] = '> ' expect(shell.prompt).eq '> ' end end describe '#eval_input' do before do @line = shell.config[:line] end would 'line' do shell.eval_input('10 ** 2') expect(shell.config[:line]).eq @line + 1 end would 'print error and increments line' do result, err = shell.eval_input('{') expect(result).eq nil expect(err).kind_of?(SyntaxError) expect(shell.config[:line]).eq @line + 1 end end describe '#running?' do would 'have complete flow' do expect(shell).not.running? mock(shell).get_input do expect(shell).running? mock(shell).puts{} nil end shell.loop expect(shell).not.running? end end describe '#stop' do would 'stop the loop if it is stopped' do mock(shell).get_input do expect(shell).running? shell.stop expect(shell).not.running? 'Rib::Skip' end shell.loop end end would 'call after_loop even if in_loop raises' do mock(shell).loop_once{ raise 'boom' } mock(Rib).warn(is_a(String)){} mock(shell).after_loop{} expect.raise(RuntimeError) do shell.loop end end would 'have empty binding' do expect(shell(:binding => nil).eval_input('local_variables').first).empty? end would 'not pollute main' do expect(shell(:binding => nil).eval_input('main').first).eq 'rib' end would 'be main' do expect(shell(:binding => nil).eval_input('self.inspect').first).eq 'main' end would 'warn on removing main' do mock(TOPLEVEL_BINDING.eval('singleton_class')).method_defined?(:main) do true end mock(Rib).warn(is_a(String)){} expect(shell(:binding => nil).eval_input('main').first).eq 'rib' end end
class TourDriver < ActiveRecord::Base belongs_to :tour belongs_to :driver validates :driver, presence: true end
class TasksController < ApplicationController before_action :set_task, only: [:show, :edit, :update, :destroy] def sort params[:order].each do |key,value| Task.find(value[:id]).update_attribute(:priority,value[:position]) end render :nothing => true end # GET /tasks def index @tasks = Task.all @incomplete = Task.where(complete: false) @complete = Task.where(complete: true) end # GET /tasks/1 def show @task = Task.find(params[:id]) end # GET /tasks/new def new @task = Task.new end # GET /tasks/1/edit def edit end # POST /tasks def create @task = Task.create!(task_params) respond_to do |format| format.html { redirect_to tasks_url } format.js end # if @task.save # redirect_to @task, notice: 'Task was successfully created.' # else # render :new # end end def complete @task = Task.find(params[:id]) @task.update(complete: true) @id = params[:id] end # PATCH/PUT /tasks/1 def update @task = Task.find(params[:id]) @task.update_attributes!(task_params) # @task.assign_attributes(task_params) # if @task.changes[complete]!=nil # last_task = Task.where(complete: @task.complete).order(priority: :desc).first # new_priority = 1 # if last_task # new_priority = last_task.priority + 1 # end # @task.priority = new_priority # end # @task.save respond_to do |format| format.html { redirect_to tasks_url } format.js end end # DELETE /tasks/1 def destroy @task.destroy respond_to do |format| format.html { redirect_to tasks_url } format.js end end private # Use callbacks to share common setup or constraints between actions. def set_task @task = Task.find(params[:id]) end # Only allow a trusted parameter "white list" through. def task_params params.require(:task).permit(:title, :description, :priority, :complete, :due_on) end end
module Store::Indices def self.table_name_prefix 'store_indices_' end end
class StudiosController < ApplicationController before_action :set_thing, only: [:show, :edit, :update, :destroy, :toggle_status] access all: [:index, :show], user: {except: [:destroy, :new, :create, :update, :edit]}, admin: :all def index q_param = params[:q] page = params[:page] @q = Studio.published.ransack q_param @studios = @q.result.page(page).per(10) end def new @studio = Studio.new end def create @studio = Studio.new(studio_params) searchable if @studio.save redirect_to studios_path else render :new end end def edit end def update if @studio.update(studio_params) searchable @studio.save redirect_to @studio else render :edit, notice: 'Your studio could not be edited' end end def show end def destroy if @studio.destroy redirect_to studios_path, notice: 'Your studio was edited successfully' else render :show, notice: 'Your studio could not be deleted' end end def toggle_status if @studio.draft? @studio.published! elsif @studio.published? @studio.draft! end redirect_to user_dashboard_admin_path, notice: "#{@studio.title} status has been updated." end private def set_thing @studio = Studio.find(params[:id]) end def studio_params params.require(:studio).permit(:title, :location) end def searchable @studio.searchable = @studio.title + @studio.location end end
Rails.application.routes.draw do #devise_for :adminusers devise_for :adminusers, :controllers => { registrations: 'registrations' } #get 'welcome/index' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" get "admin" => "admin/pages#index" namespace :admin do resources :posts resources :categories resources :images get 'writers', to: 'pages#writers' end #root 'admin/posts#index' scope module: 'frontend' do get "kategorien" => "pages#categories", as: "kategorien" get "beitrag/:id" => "pages#show", as: "beitrag" get "info", to: "pages#about", as: "info" get "impressum", to: "pages#imprint", as: "impressum" end root :to => "frontend/pages#index" match '*path', via: [:get, :post, :put, :options, :propfind], to: 'frontend/pages#error_404' match '/', via: [:options, :post, :webdav], to: 'frontend/pages#error_404' end
class CreateWildernesses < ActiveRecord::Migration[5.1] def change create_table :wildernesses do |t| t.string :name t.string :coords, limit: 9 t.integer :world_id t.blob :data t.timestamps end end end
require 'colorize' class Jar attr_reader :path, :files def initialize(path) @path = path @files = %x[jar tf #{path} 2>&1 ].lines end def match?(re) @matches = @files.select{|f| f =~ re} not @matches.empty? end def matches path.colorize(:light_blue) + "\n" + @matches.join + "\n" end end
# -*- mode: ruby -*- # vi: set ft=ruby : num_of_nodes = 1 # Vagrantfile API/syntax version. Don't touch unless you know what you're doing! VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "centos-6.5-x86_64" config.vm.box_url = "packer/build/#{config.vm.box}.box" # config.vm.network :forwarded_port, guest: 80, host: 8080 config.vm.network :public_network # config.vm.synced_folder "../data", "/vagrant_data" config.vm.provider :virtualbox do |vb| vb.gui = false vb.customize ["modifyvm", :id, "--memory", "512"] vb.customize ["modifyvm", :id, "--cpus", "2"] end config.vm.define :rabbitmq do |n| n.vm.hostname = "rabbitmq" n.vm.network :private_network, ip: "192.168.0.2" n.vm.provision :chef_solo do |chef| chef.cookbooks_path = "cookbooks" chef.add_recipe "rabbitmq::default" chef.add_recipe "rabbitmq::plugin_management" chef.add_recipe "rabbitmq::virtualhost_management" chef.add_recipe "rabbitmq::user_management" chef.add_recipe "rabbitmq::mgmt_console" chef.json = { :rabbitmq => { :version => '3.2.4', :virtualhosts => ['/mcollective'], :enabled_users => [ { :name => 'admin', :password => 'changeme', :tag => 'administrator', :rights => [ { :vhost => "/mcollective", :conf => ".*", :write => ".*", :read => ".*" } ] },{ :name => 'mcollective', :password => 'changeme', :rights => [ { :vhost => "/mcollective", :conf => ".*", :write => ".*", :read => ".*" } ] } ], :ssl => true, :ssl_port => '5671', :ssl_cacert => '/vagrant/certs/rabbitmq/cacert.pem', :ssl_cert => '/vagrant/certs/rabbitmq/server/cert.pem', :ssl_key => '/vagrant/certs/rabbitmq/server/key.pem', :ssl_verify => 'verify_peer', :stomp => true } } end n.vm.provision "shell", inline: "wget -O /usr/local/bin/rabbitmqadmin http://127.0.0.1:15672/cli/rabbitmqadmin && chmod +x /usr/local/bin/rabbitmqadmin" n.vm.provision "shell", inline: '/usr/local/bin/rabbitmqadmin declare exchange --user=admin --password=changeme --vhost="/mcollective" name=mcollective_broadcast type=topic' n.vm.provision "shell", inline: '/usr/local/bin/rabbitmqadmin declare exchange --user=admin --password=changeme --vhost="/mcollective" name=mcollective_directed type=direct' end config.vm.define :'mco-client' do |n| n.vm.hostname = 'mco-client' n.vm.network :private_network, ip: "192.168.0.3" n.vm.provision :chef_solo do |chef| chef.cookbooks_path = "cookbooks" chef.add_recipe "mcollective::default" chef.json = { :mcollective => { :connector => "rabbitmq", :rabbitmq => { :vhost => "/mcollective" }, :stomp => { :hostname => "192.168.0.2", :port => 61613, :username => "mcollective", :password => "changeme", :ssl => { :enabled => true, :port => "61614", :ca => "/vagrant/certs/rabbitmq/cacert.pem", :cert => "/vagrant/certs/rabbitmq/client/cert.pem", :key => "/vagrant/certs/rabbitmq/client/key.pem", :fallback => false } } } } end end num_of_nodes.times do |c| config.vm.define :"mco-node-#{c}" do |n| n.vm.hostname = "mco-node-#{c}" n.vm.network :private_network, ip: "192.168.0.#{c+4}" n.vm.provision :chef_solo do |chef| chef.cookbooks_path = "cookbooks" chef.add_recipe "mcollective::server" chef.json = { :mcollective => { :connector => "rabbitmq", :rabbitmq => { :vhost => "/mcollective" }, :stomp => { :hostname => "192.168.0.2", :port => "61613", :username => "mcollective", :password => "changeme", :ssl => { :enabled => true, :port => "61614", :ca => "/vagrant/certs/rabbitmq/cacert.pem", :cert => "/vagrant/certs/rabbitmq/client/cert.pem", :key => "/vagrant/certs/rabbitmq/client/key.pem", :fallback => false } } } } end end end end
require 'rails_helper' RSpec.describe Transaction, type: :model do describe 'associations' do it { should belong_to(:lender).class_name('User') } it { should belong_to(:borrower).class_name('User') } it { should belong_to(:thing) } it { should have_db_index(:borrower_id) } it { should have_db_index(:lender_id) } it { should have_db_index(:thing_id) } end end
class Like < ActiveRecord::Base belongs_to :answer belongs_to :user validates_uniqueness_of :answer_id, scope: :user_id end
require 'cells_helper' RSpec.describe Balance::Cell::Index do let(:account) { create_account } let(:owner) { account.owner } let(:current_account) { account } it 'asks me to connect to AwardWallet' do rendered = cell(account).() expect(rendered).to have_content 'Connect your AwardWallet account to Abroaders' expect(rendered).to have_link 'Connect to AwardWallet' expect(rendered).to have_no_content "You're connected to your AwardWallet account" expect(rendered).to have_no_link 'Manage settings' end let(:sync_btn_text) { 'Sync Balances' } example 'no "Sync Balances" button' do rendered = cell(account).() expect(rendered).not_to have_button sync_btn_text end context 'when account is connected to AwardWallet' do before do account.build_award_wallet_user(loaded: true, user_name: 'AWUser') end it 'has link to AW settings page' do rendered = cell(account).() expect(rendered).to have_content "You're connected to your AwardWallet account" expect(rendered).to have_content 'AWUser' expect(rendered).to have_link 'Manage settings', href: integrations_award_wallet_settings_path expect(rendered).to have_no_content 'Connect your AwardWallet account to Abroaders' expect(rendered).to have_no_link 'Connect to AwardWallet' end it 'has a link to sync balances' do rendered = cell(account).() expect(rendered).to have_button sync_btn_text end end example 'solo account with no balances' do rendered = cell(account).() expect(rendered).to have_selector 'h1', text: 'My points' expect(rendered).to have_content 'No points balances' end example 'solo account with balances' do balances = Array.new(2) { create_balance(person: owner) } rendered = cell(account).() expect(rendered).to have_selector 'h1', text: 'My points' expect(rendered).not_to have_content 'No points balances' expect(rendered).to have_content balances[0].currency_name expect(rendered).to have_content balances[1].currency_name end describe 'couples account' do let!(:companion) { account.create_companion!(first_name: 'Gabi') } example 'neither person has balances' do rendered = cell(account).() expect(rendered).to have_selector 'h1', text: "Erik's points" expect(rendered).to have_selector 'h1', text: "Gabi's points" expect(rendered).to have_content 'No points balances', count: 2 end example 'one person has no balances' do create_balance(person: owner) rendered = cell(account).() expect(rendered).to have_selector 'h1', text: "Erik's points" expect(rendered).to have_selector 'h1', text: "Gabi's points" expect(rendered).to have_content owner.balances[0].currency_name expect(rendered).to have_content 'No points balances', count: 1 end example 'both people have balances' do ob = create_balance(person: owner) cb = create_balance(person: companion) rendered = cell(account).() expect(rendered).to have_selector 'h1', text: "Erik's points" expect(rendered).to have_selector 'h1', text: "Gabi's points" expect(rendered).to have_content ob.currency_name expect(rendered).to have_content cb.currency_name expect(rendered).to have_no_content 'No points balances' end end it 'avoids XSS' do owner.update!(first_name: '<script>') account.create_companion!(first_name: '</script>') rendered = raw_cell(account) expect(rendered).to include "&lt;script&gt;" expect(rendered).to include "&lt;/script&gt;" end end
module Type class EditPresenter def record @record ||= Setting.find_by!(key: 'type') end def available_types ::Runner::ContainerBuilder::TYPE_LABEL_MAPPING end end end
# == Schema Information # # Table name: users # # id :integer not null, primary key # email :string(255) default(""), not null # encrypted_password :string(255) default(""), not null # reset_password_token :string(255) # reset_password_sent_at :datetime # admin :boolean # remember_created_at :datetime # sign_in_count :integer default(0), not null # current_sign_in_at :datetime # last_sign_in_at :datetime # current_sign_in_ip :string(255) # last_sign_in_ip :string(255) # created_at :datetime # updated_at :datetime # firstname :string(255) # lastname :string(255) # class User < ActiveRecord::Base has_paper_trail # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable before_create :ensure_at_least_one_admin has_many :products has_many :reservations has_many :visits validates :firstname, presence: true validates :lastname, presence: true # By default this will make sure the first user to registers gets admin status def ensure_at_least_one_admin unless User.any? self.admin = true end end def self.last_signups(count) order(created_at: :desc).limit(count).select("id", "email", "created_at") end def fullname "#{firstname} #{lastname}" end def online? return false unless self.update_at > 5.minutes.ago end end
# # Cookbook Name:: git # Recipe:: windows # # Copyright 2008-2012, Opscode, Inc. # # 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. # file_name = 'Git-1.7.11-preview20120710.exe' file_checksum = 'cc84132e0acc097fc42a9370214a9ce0ff942e1a8237f11d8cb051cb6043e0d5' remote_file "#{Chef::Config[:file_cache_path]}/#{file_name}" do source "http://msysgit.googlecode.com/files/#{file_name}" checksum file_checksum not_if { File.exists?("#{Chef::Config[:file_cache_path]}/#{file_name}") } end windows_batch "install git" do command "#{Chef::Config[:file_cache_path]}/#{file_name} /verysilent /dir=C:\\git" creates "C:\\git\\cmd\\git.exe" end windows_path "C:\\git\\cmd" do action :add end
require 'skit/amqp/runner' describe Skit::AMQP::Runner do let(:instance) { Skit::AMQP::Runner.new } before :all do DaemonKit::Initializer.run.initialize_logger end describe '.new' do subject { instance } it 'loads amqp config' do expect(subject.instance_variable_get('@config')).to be_instance_of(Hash) end end describe '#run' do let(:connection_double) do double('AMQP Connection', on_tcp_connection_loss: nil, on_recovery: nil) end subject { instance.run { @testing } } before do expect(AMQP).to receive(:start).and_yield(connection_double) end it 'runs' do subject end end end
# ---------------------------------------------------------------------------- # Frozen-string-literal: true # Copyright: 2012 - 2016 - MIT License # Encoding: utf-8 # ---------------------------------------------------------------------------- require "nokogiri" module Jekyll module RSpecHelpers class ContextThief < Liquid::Tag class << self attr_accessor :context end # ---------------------------------------------------------------------- def render(context) self.class.context = context end end # ------------------------------------------------------------------------ # Allows you to get a real context context, to test methods directly # if you need to, most can be tested indirectly. # ------------------------------------------------------------------------ def build_context site = stub_jekyll_site site.liquid_renderer.file("").parse("{% context_thief %}") \ .render!(site.site_payload, :registers => { :site => site }) ContextThief.context end # ------------------------------------------------------------------------ def fragment(html) Nokogiri::HTML.fragment(html) end # ------------------------------------------------------------------------ # Allows you to run something capturing all errors and output so you can # run a test cleanly without a bunch of noise, nobody likes noise when they # are just trying to see the result of a failed test. # ------------------------------------------------------------------------ def silence_stdout(return_stringio = false) old_stdout = $stdout; old_stderr = $stderr $stdout = stdout = StringIO.new $stderr = stderr = StringIO.new output = yield if return_stringio return [ stdout.string, stderr.string ] else return output end ensure $stdout = old_stdout $stderr = old_stderr end # ------------------------------------------------------------------------ # Uses `#silence_stdout` to return output to you without you having # to use true or false on `#silence_stoudt`. # ------------------------------------------------------------------------ def capture_stdout(&block) silence_stdout true, &block end # ------------------------------------------------------------------------ # Stubs the asset config on Jekyll for you, this is meant to be used # in a new context or at the top of a context so that you can stub the # configuration and have it reset afterwards. # ------------------------------------------------------------------------ def stub_asset_config(inst, hash = nil) (hash = inst; inst = nil) if inst.is_a?(Hash) inst = @site || site unless inst hash = Jekyll::Assets::Config.merge(hash) allow(inst).to receive(:config).and_return(inst.config.merge({ "assets" => hash })) end # ------------------------------------------------------------------------ def stub_env_config(inst, hash = nil) (hash = inst; inst = nil) if inst.is_a?(Hash) inst = @env || env unless inst hash = Jekyll::Utils.deep_merge_hashes(inst.asset_config, hash) allow(inst).to receive(:asset_config).and_return(hash) end # ------------------------------------------------------------------------ # Strips ANSI from the output so that you can test just a plain text # string without worrying about whether colors are there or not, this is # mostly useful for testing log output or other helpers. # ------------------------------------------------------------------------ def strip_ansi(str) str.gsub(/\e\[(?:\d+)(?:;\d+)?m/, "") end # ------------------------------------------------------------------------ # Stubs the Jekyll site with your configuration, most of the time you # won't do it this way though, because you can just initialize the default # configuration with our merges and stub the configuration pieces. # ------------------------------------------------------------------------ def stub_jekyll_site(opts = {}) path = File.expand_path("../../fixture", __FILE__) Jekyll::RSpecHelpers.cleanup_trash silence_stdout do Jekyll::Site.new(Jekyll.configuration(opts.merge({ "source" => path, "destination" => File.join(path, "_site") }))).tap(&:read) end end # ------------------------------------------------------------------------ # See: `#stub_jekyll_site` except this also kicks a process so that # do both the building and the processing all in one shot. # ------------------------------------------------------------------------ def stub_jekyll_site_with_processing(oth_opts = {}) site = stub_jekyll_site(oth_opts) silence_stdout { site.process } site end # ------------------------------------------------------------------------ # Pulls a file and passes the data to you (from _site), this does # no checking so it will raise an error if there is no file that you wish # to pull, so beware of that when testing. # ------------------------------------------------------------------------ def get_stubbed_file(file) path = File.expand_path("../../fixture/_site", __FILE__) File.read(File.join(path, file)) end # ------------------------------------------------------------------------ # Cleanup after ourselves when testing, removing the data that we and # through us Jekyll created, so that if we test again there is nothing but # clean data to test with, and not dirty old data. # ------------------------------------------------------------------------ def self.cleanup_trash %W(.asset-cache .jekyll-metadata _site).each do |v| FileUtils.rm_rf(File.join(File.expand_path("../../fixture", __FILE__), v)) end end end end # ---------------------------------------------------------------------------- Liquid::Template.register_tag "context_thief", \ Jekyll::RSpecHelpers::ContextThief # ---------------------------------------------------------------------------- RSpec.configure do |c| c.include Jekyll::RSpecHelpers c.before :all do Jekyll::RSpecHelpers.cleanup_trash end # c.after :all do Jekyll::RSpecHelpers.cleanup_trash end end