text
stringlengths
10
2.61M
module Devise module Models module Webauthn2fAuthenticatable extend ActiveSupport::Concern included do has_many :credentials, class_name: "::Devise::Webauthn::Credential" after_initialize do self.webauthn_id ||= ::WebAuthn.generate_user_id end end end end end
require 'database_connection' describe DatabaseConnection do describe '.setup' do it 'sets up a connection to a database through SQLite3' do expect(SQLite3::Database).to receive(:new).with('project_org_test.db') DatabaseConnection.setup('project_org_test.db') end it 'this connection is persistent' do # Grab the connection as a return value from the .setup method connection = DatabaseConnection.setup('project_org_test.db') expect(DatabaseConnection.connection).to eq(connection) end end describe '.query' do it 'executes a query via SQLite' do connection = DatabaseConnection.setup('project_org_test.db') quote = Quotes.create(date_created:'01/09/2021', client_id:'3', project_scope:'Project scope 3') results = DatabaseConnection.query("SELECT * FROM quotes;") expect(connection).to receive(:execute).with("SELECT * FROM quotes;") DatabaseConnection.query("SELECT * FROM quotes;") p results p quote end end end
class UserPicture < ActiveRecord::Base mount_uploader :photo, ImageUploader belongs_to :user validates :photo, :presence => true end
# LEARN RUBY THE HARD WAY - 3 EDITION # ---------------------------------------------------------------------------- # Exercise 1 : A Good First Program # --------------------------------- # Type the following text into a single file. Ruby files end with .rb puts "Hello World!" puts "Hello Again" puts "I like typing this." puts "This is fun." puts "Yay! Printing." puts "I'd much rather you 'not'." puts 'I "said" do not touch this.' # So to run this program type: # # $ ruby 002-exercise01.rb # # The ouput of the program is: # # Hello World! # Hello Again # I like typing this. # This is fun. # Yay! Printing. # I'd much rather you 'not'. # I "said" do not touch this. # # # Study Drills # ------------ # The study drills contain things you should try to do. If you can't, skip it # and come back later. For this exercise, try this things: # # [1] Make your script print another line. # [2] Make your script print only one of the lines. # [3] Put a # (octothorpe) character at the beginning of a line. What did it # do? Try to find out what this character does. # # From now on, I won't explain how each exercise works unless an exercise is # different.
# encoding: utf-8 # # This file is a part of Redmine Products (redmine_products) plugin, # customer relationship management plugin for Redmine # # Copyright (C) 2011-2016 Kirill Bezrukov # http://www.redminecrm.com/ # # redmine_products is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # redmine_products is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with redmine_products. If not, see <http://www.gnu.org/licenses/>. module ProductsHelper def product_tag(product, options={}) image_size = options.delete(:size) || 16 if product.visible? && !options[:no_link] image = link_to(product_image_tag(product, :size => image_size), product_path(product), :class => "avatar") product_name = link_to product.name, product_path(product) else image = product_image_tag(product, :size => image_size) product_name = product.name end case options.delete(:type).to_s when "image" image.html_safe when "plain" product_name.html_safe else content_tag(:span, "#{image} #{product_name}".html_safe, :class => "product") end end def products_check_box_tags(name, products) s = '' products.each do |product| s << "<label>#{ check_box_tag name, product.id, false, :id => nil } #{product_tag(product, :no_link => true)}#{' (' + product.price_to_s + ')' unless product.price.blank?}</label>\n" end s.html_safe end def product_categories_for_select @product_categories ||= ProductCategory.order(:lft).all end def orders_contacts_for_select(project, options={}) scope = Contact.where({}) scope = scope.joins(:projects).uniq.where(Contact.visible_condition(User.current)) scope = scope.joins(:orders) scope = scope.where("(#{Project.table_name}.id <> -1)") scope = scope.where(:orders => {:project_id => project}) if project scope.limit(options[:limit] || 500).map{|c| [c.name, c.id.to_s]} end def label_with_currency(label, currency) l(label).mb_chars.capitalize.to_s + (currency.blank? ? '' : " (#{currency})") end def product_list_styles_for_select list_styles = [[l(:label_crm_list_excerpt), "list_excerpt"]] end def products_list_style list_styles = product_list_styles_for_select.map(&:last) if params[:products_list_style].blank? list_style = list_styles.include?(session[:products_list_style]) ? session[:products_list_style] : ProductsSettings.default_list_style else list_style = list_styles.include?(params[:products_list_style]) ? params[:products_list_style] : ProductsSettings.default_list_style end session[:products_list_style] = list_style end def collection_product_status_names [[:active, Product::ACTIVE_PRODUCT], [:inactive, Product::INACTIVE_PRODUCT]] end def collection_product_statuses [[l(:label_products_status_active), Product::ACTIVE_PRODUCT], [l(:label_products_status_inactive), Product::INACTIVE_PRODUCT]] end def collection_product_categories ProductCategory.all.map{|k| [k.name, k.id.to_s]} end def products_is_no_filters (params[:status_id] == 'o' && (params[:period].blank? || params[:period] == 'all') && params[:contact_id].blank?) end def product_tag_url(tag_name, options={}) {:controller => 'products', :action => 'index', :set_filter => 1, :project_id => @project, :fields => [:tags], :values => {:tags => [tag_name]}, :operators => {:tags => '='}}.merge(options) end def product_category_url(category_id, options={}) {:controller => 'products', :action => 'index', :set_filter => 1, :project_id => @project, :fields => [:category_id], :values => {:category_id => [category_id]}, :operators => {:category_id => '='}}.merge(options) end def product_category_tree_tag(product, options={}) return "" if product.category.blank? product.category.self_and_ancestors.map do |category| link_to category.name, product_category_url(category.id, options) end.join(' &#187; ').html_safe end def product_tag_link(tag_name, options={}) style = ContactsSetting.monochrome_tags? ? {} : {:style => "background-color: #{tag_color(tag_name)}"} tag_count = options.delete(:count) tag_title = tag_count ? "#{tag_name} (#{tag_count})" : tag_name link = link_to tag_title, product_tag_url(tag_name), options content_tag(:span, link, {:class => "tag-label-color"}.merge(style)) end def product_tag_links(tag_list, options={}) content_tag( :span, tag_list.map{|tag| product_tag_link(tag, options)}.join(' ').html_safe, :class => "tag_list") if tag_list end def product_category_tree_options_for_select(product_categories, options = {}) s = '' ProductCategory.category_tree(product_categories) do |product_category, level| name_prefix = (level > 0 ? '&nbsp;' * 2 * level + '&#187; ' : '').html_safe tag_options = {:value => product_category.id} if product_category == options[:selected] || (options[:selected].respond_to?(:include?) && options[:selected].include?(product_category)) tag_options[:selected] = 'selected' else tag_options[:selected] = nil end tag_options.merge!(yield(product_category)) if block_given? s << content_tag('option', name_prefix + h(product_category.name), tag_options) end s.html_safe end def product_image_tag(product, options = { }) options[:size] ||= "64" options[:size] = options[:size].to_s options[:width] ||= options[:size] options[:height] ||= options[:size] options.merge!({:class => "gravatar"}) if (image = product.image) && image.readable? product_image_url = url_for :controller => "attachments", :action => "contacts_thumbnail", :id => image, :size => options[:size] if options[:full_size] link_to(image_tag(product_image_url, options), :controller => 'attachments', :action => 'download', :id => image, :filename => image.filename) else image_tag(product_image_url, options) end else image_tag("product.png", options.merge({:plugin => "redmine_products"})) end end def product_line_to_s(line) "#{line.product ? line.product.name : line.description} - #{line.price_to_s} x #{line.quantity}#{' - ' + "%.2f" % line.discount.to_f + '%' unless line.discount.blank? || line.discount == 0} = #{line.total_to_s}" end def order_status_tag(order_status) return '' unless order_status status_tag = content_tag(:span, order_status.name) content_tag(:span, status_tag, :class => "tag-label-color order-status", :style => "background-color:#{order_status.color_name};color:white;") end def collection_for_order_status_for_select OrderStatus.order(:position).collect{|s| [s.name, s.id.to_s]} end def orders_list_styles_for_select list_styles = [[l(:label_crm_list_excerpt), "list_excerpt"]] end def orders_list_style list_styles = orders_list_styles_for_select.map(&:last) if params[:orders_list_style].blank? list_style = list_styles.include?(session[:orders_list_style]) ? session[:orders_list_style] : ProductsSettings.default_list_style else list_style = list_styles.include?(params[:orders_list_style]) ? params[:orders_list_style] : ProductsSettings.default_list_style end session[:orders_list_style] = list_style end def orders_link_to_remove_fields(name, f, options={}) f.hidden_field(:_destroy) + link_to_function(name, "remove_order_fields(this);", options) end def orders_link_to_add_fields(name, f, association, options={}) new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder| render(association.to_s.singularize + "_fields", :f => builder) end link_to_function(name, "add_fields(this, '#{association}', '#{escape_javascript(fields)}')", options={}) end def retrieve_orders_query if !params[:order_query_id].blank? cond = "project_id IS NULL" cond << " OR project_id = #{@project.id}" if @project @query = OrderQuery.find(params[:order_query_id], :conditions => cond) raise ::Unauthorized unless @query.visible? @query.project = @project session[:orders_query] = {:id => @query.id, :project_id => @query.project_id} sort_clear elsif api_request? || params[:set_filter] || session[:orders_query].nil? || session[:orders_query][:project_id] != (@project ? @project.id : nil) # Give it a name, required to be valid @query = OrderQuery.new(:name => "_") @query.project = @project @query.build_from_params(params) session[:orders_query] = {:project_id => @query.project_id, :filters => @query.filters, :group_by => @query.group_by, :column_names => @query.column_names} else # retrieve from session @query = OrderQuery.find(session[:orders_query][:id]) if session[:orders_query][:id] @query ||= OrderQuery.new(:name => "_", :filters => session[:orders_query][:filters], :group_by => session[:orders_query][:group_by], :column_names => session[:orders_query][:column_names]) @query.project = @project end end end
case node.platform when "centos","redhat","amazon" execute "copy init file" do command "cp #{node['hyclops']['download_path']}/misc/init.d/redhat/hyclops /etc/init.d/" action :run not_if{ ::File::exist?('/etc/init.d/hyclops') } end when "ubuntu","debian" execute "copy init file" do command "cp #{node['hyclops']['download_path']}/misc/init.d/ubuntu/hyclops.conf /etc/init/" action :run not_if{ ::File::exist?('/etc/init/hyclops.conf') } end end
class RemoveStoreTypeFromStores < ActiveRecord::Migration def change remove_column :stores, :store_type end end
require "RMagick" class MemeGenerator attr_reader :source_filepath, :top_text, :bottom_text, :result_filepath def initialize(source_filepath, top_text, bottom_text, result_filepath = "mem.jpg") @source_filepath = source_filepath @top_text = top_text @bottom_text = bottom_text @result_filepath = result_filepath end def file_exist? File.file?(@source_filepath) end def source_file @source_file ||= Magick::ImageList.new(@source_filepath) end def meme @meme ||= Magick::Draw.new() end def generate! set_default_meme add_text Magick::NorthGravity, top_text add_text Magick::SouthGravity, bottom_text source_file.write(@result_filepath) end private def set_default_meme meme.pointsize = 52 meme.stroke = 'transparent' meme.fill = '#ffffff' meme.font_weight = Magick::BoldWeight meme.font_family = "Impact" end def add_text(gravity, text) meme.gravity = gravity meme.annotate(source_file, 0, 0, 0, 60, text.upcase) end end
class CreateEvaluations < ActiveRecord::Migration[5.2] def change create_table :evaluations do |t| t.integer :number_fruit t.float :height t.integer :overall_health t.text :notes t.belongs_to :plant, foreign_key: true t.timestamps end end end
# This helper provides at least a x2 speed increase over the 'spec_slow_helper'. # # To validate this assumption, find a spec for an ActiveRecord object, and run # with `rspec -r spec/spec_active_record_helper.rb ./path/to/spec.rb` # # Example: # $ time rspec -r spec/spec_active_record_helper.rb spec/features/new_user_input_to_in_memory_spec.rb # # real 0m1.576s # user 0m1.093s # sys 0m0.295s # # Compared to `rspec -r spec/spec_slow_helper.rb ./path/to/spec.rb` # # Example: # $ time rspec -r spec/spec_slow_helper.rb spec/features/new_user_input_to_in_memory_spec.rb # # real 0m3.546s # user 0m2.417s # sys 0m0.702s require 'active_record' require 'spec_fast_helper' if !defined?(Rails) # Sometimes this will be invoked when Rails is defined. In that case the relative # path is ../internal. When Rails is not defined the relative path is different. # By providing an absolute path, I avoid either of those silly things. database = File.expand_path('../internal/db/development.sqlite3', __FILE__) connection_info = { adapter: 'sqlite3', database: database, pool: 5, timeout: 5000 } ActiveRecord::Base.establish_connection(connection_info) end RSpec.configure do |config| config.around do |example| ActiveRecord::Base.transaction do example.run fail ActiveRecord::Rollback end end end
class CreateMicrocosms < ActiveRecord::Migration[5.1] def change create_table :microcosms do |t| t.string :name, :null => false t.string :key, :null => false t.integer :members_num, :null => false t.timestamps end add_index :microcosms, :key, unique: true end end
require 'rails_helper' describe HomeController do render_views let!(:current) { create(:location, current: true) } describe 'GET #map' do it 'renders the home/map template' do get :map expect(response).to render_template('home/map') end end describe 'GET #about' do it 'renders the home/about template' do get :about expect(response).to render_template('home/about') end end describe 'GET #colophon' do it 'renders the home/colophon template' do get :colophon expect(response).to render_template('home/colophon') end end describe 'GET #sitemap' do it 'renders home/sitemap.xml' do # post = create(:post) # user = create(:user) # current_location = create(:location, current: true) # exp = create(:experience, user: user) # get :sitemap, format: :xml # expect(response).to render_template('home/sitemap.xml') end end end
=begin Sources will be the original files Documentation - PSQ Master File?? =end module ETL class PsqLoader EVENT_NAME = 'post_sleep_questionnaire' def initialize(source, documentation) begin data_info = { path: source.location, skip_lines: 1, header: true } init_column_map init_object_map @db_loader = ETL::DatabaseLoader.new(data_info, @object_map, @column_map, source, documentation) rescue => error LOAD_LOG.info "#### Setup Error: #{error.message}\n\nBacktrace:\n#{error.backtrace}" end end private # subject_code sleep_period lights_out_labtime_decimal q_1 q_2 q_3 q_4 q_4a q_5 q_6 q_7 q_8 notes def init_column_map @column_map = [ { target: :subject, field: :subject_code }, { target: :datum, field: :sleep_period, event_name: EVENT_NAME }, { target: :event, field: :labtime_decimal }, { target: :event, field: :labtime_year }, { target: :none }, { target: :none }, { target: :none }, { target: :datum, field: :question_1, event_name: EVENT_NAME }, { target: :datum, field: :question_2, event_name: EVENT_NAME }, { target: :datum, field: :question_3, event_name: EVENT_NAME }, { target: :datum, field: :question_4, event_name: EVENT_NAME }, { target: :datum, field: :question_4a, event_name: EVENT_NAME }, { target: :datum, field: :question_5, event_name: EVENT_NAME }, { target: :datum, field: :question_6, event_name: EVENT_NAME }, { target: :datum, field: :question_7, event_name: EVENT_NAME }, { target: :datum, field: :question_8, event_name: EVENT_NAME }, { target: :event, field: :notes, event_name: EVENT_NAME } ] end def init_object_map @object_map = [ { class: Subject, existing_records: {action: :ignore, find_by: [:subject_code]} }, { class: Event, event_name: EVENT_NAME, existing_records: { action: :destroy, find_by: [:name, :subject_id]} } ] end end end
# frozen_string_literal: true require 'spec_helper' require 'rspec/sleeping_king_studios/examples/rspec_matcher_examples' require 'support/matchers/be_a_constraint_matcher' RSpec.describe Spec::Support::Matchers::BeAConstraintMatcher do include RSpec::SleepingKingStudios::Examples::RSpecMatcherExamples shared_context 'when the expected constraint is a Class' do let(:expected_constraint) { Spec::ExampleConstraint } example_class 'Spec::ExampleConstraint', Stannum::Constraints::Base end shared_context 'when the expected constraint is a matcher' do let(:expected_constraint) { be_a(Spec::ExampleConstraint) } example_class 'Spec::ExampleConstraint', Stannum::Constraints::Base end shared_context 'when there are expected options' do subject(:matcher) do described_class.new(expected_constraint).with_options(**expected_options) end let(:expected_options) do { language: 'Ada', log_level: 'panic', strict: true } end end subject(:matcher) { described_class.new(expected_constraint) } let(:expected_constraint) { nil } describe '.new' do it { expect(described_class).to be_constructible.with(0..1).arguments } end describe '#description' do let(:expected) { 'be a constraint' } it { expect(matcher).to respond_to(:description).with(0).arguments } it { expect(matcher.description).to be == expected } # rubocop:disable RSpec/RepeatedExampleGroupBody wrap_context 'when the expected constraint is a Class' do let(:expected) { 'be a Spec::ExampleConstraint' } it { expect(matcher.description).to be == expected } wrap_context 'when there are expected options' do let(:expected) do %(#{super()} with options language: "Ada", log_level: "panic") \ ', strict: true' end it { expect(matcher.description).to be == expected } end end wrap_context 'when the expected constraint is a matcher' do let(:expected) { 'be a Spec::ExampleConstraint' } it { expect(matcher.description).to be == expected } wrap_context 'when there are expected options' do let(:expected) do %(#{super()} with options language: "Ada", log_level: "panic") \ ', strict: true' end it { expect(matcher.description).to be == expected } end end # rubocop:enable RSpec/RepeatedExampleGroupBody wrap_context 'when there are expected options' do let(:expected) do %(#{super()} with options language: "Ada", log_level: "panic") \ ', strict: true' end it { expect(matcher.description).to be == expected } end end describe '#does_not_match?' do let(:failure_message_when_negated) do "expected #{actual.inspect} not to be a constraint" end it { expect(matcher).to respond_to(:does_not_match?).with(1).argument } describe 'with nil' do let(:actual) { nil } include_examples 'should pass with a negative expectation' end describe 'with an Object' do let(:actual) { Object.new.freeze } include_examples 'should pass with a negative expectation' end describe 'with a constraint' do let(:actual) { Stannum::Constraint.new } include_examples 'should fail with a negative expectation' end wrap_context 'when the expected constraint is a Class' do let(:failure_message_when_negated) do "expected #{actual.inspect} not to be a #{expected_constraint.name}" end describe 'with a constraint that does not match the expected constraint' \ do let(:actual) { Stannum::Constraint.new } include_examples 'should pass with a negative expectation' end describe 'with a constraint that matches the expected constraint' do let(:actual) { Spec::ExampleConstraint.new } include_examples 'should fail with a negative expectation' end wrap_context 'when there are expected options' do let(:actual) { Stannum::Constraint.new } let(:error_message) do '`expect().not_to be_a_constraint().with_options()` is not supported' end it 'should raise an error' do expect { matcher.does_not_match?(actual) } .to raise_error StandardError, error_message end end end wrap_context 'when the expected constraint is a matcher' do let(:failure_message_when_negated) do "expected #{actual.inspect} not to #{expected_constraint.description}" end describe 'with a constraint that does not match the expected constraint' \ do let(:actual) { Stannum::Constraint.new } include_examples 'should pass with a negative expectation' end describe 'with a constraint that matches the expected constraint' do let(:actual) { Spec::ExampleConstraint.new } include_examples 'should fail with a negative expectation' end wrap_context 'when there are expected options' do let(:actual) { Stannum::Constraint.new } let(:error_message) do '`expect().not_to be_a_constraint().with_options()` is not supported' end it 'should raise an error' do expect { matcher.does_not_match?(actual) } .to raise_error StandardError, error_message end end end wrap_context 'when there are expected options' do let(:actual) { Stannum::Constraint.new } let(:error_message) do '`expect().not_to be_a_constraint().with_options()` is not supported' end it 'should raise an error' do expect { matcher.does_not_match?(actual) } .to raise_error StandardError, error_message end end end describe '#expected' do include_examples 'should have reader', :expected, nil # rubocop:disable RSpec/RepeatedExampleGroupBody wrap_context 'when the expected constraint is a Class' do it { expect(matcher.expected).to be expected_constraint } end wrap_context 'when the expected constraint is a matcher' do it { expect(matcher.expected).to be expected_constraint } end # rubocop:enable RSpec/RepeatedExampleGroupBody end describe '#expected_options' do include_examples 'should have reader', :expected_options, -> { be == {} } wrap_context 'when there are expected options' do it { expect(matcher.expected_options).to be == expected_options } end end describe '#failure_message' do it { expect(matcher).to respond_to(:failure_message).with(0).arguments } end describe '#failure_message_when_negated' do it 'should define the method' do expect(matcher) .to respond_to(:failure_message_when_negated) .with(0).arguments end end describe '#matches?' do let(:failure_message) { "expected #{actual.inspect} to be a constraint" } def tools SleepingKingStudios::Tools::Toolbelt.instance end it { expect(matcher).to respond_to(:matches?).with(1).argument } describe 'with nil' do let(:actual) { nil } let(:failure_message) do "#{super()}, but is not a constraint" end include_examples 'should fail with a positive expectation' end describe 'with an Object' do let(:actual) { Object.new.freeze } let(:failure_message) do "#{super()}, but is not a constraint" end include_examples 'should fail with a positive expectation' end describe 'with a constraint' do let(:actual) { Stannum::Constraint.new } include_examples 'should pass with a positive expectation' end describe 'with a constraint with options' do let(:options) { { key: 'value' } } let(:actual) { Stannum::Constraint.new(**options) } include_examples 'should pass with a positive expectation' end wrap_context 'when the expected constraint is a Class' do let(:failure_message) do "expected #{actual.inspect} to be a #{expected_constraint.name}" end describe 'with a constraint that does not match the expected constraint' \ do let(:actual) { Stannum::Constraint.new } let(:failure_message) do "#{super()}, but is not an instance of #{expected_constraint}" end include_examples 'should fail with a positive expectation' end describe 'with a constraint that matches the expected constraint' do let(:actual) { Spec::ExampleConstraint.new } include_examples 'should pass with a positive expectation' end describe 'with a constraint with options' do let(:options) { { key: 'value' } } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should pass with a positive expectation' end wrap_context 'when there are expected options' do let(:diff_matcher) do RSpec::SleepingKingStudios::Matchers::Core::DeepMatcher .new(expected_options) .tap { |matcher| matcher.matches?(actual.options) } end let(:failure_message) do "#{super()}, but the options do not match:\n" + tools.str.indent(diff_matcher.failure_message, 2) end describe 'with a constraint with missing options' do let(:options) { {} } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with changed options' do let(:options) { expected_options.merge(language: 'Basic') } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with added options' do let(:options) { expected_options.merge(compiler: 'gcc') } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with matching options' do let(:options) { expected_options } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should pass with a positive expectation' end end end wrap_context 'when the expected constraint is a matcher' do let(:failure_message) do expected_constraint .tap { expected_constraint.matches?(actual) } .failure_message end describe 'with a constraint that does not match the expected constraint' \ do let(:actual) { Stannum::Constraint.new } include_examples 'should fail with a positive expectation' end describe 'with a constraint that matches the expected constraint' do let(:actual) { Spec::ExampleConstraint.new } include_examples 'should pass with a positive expectation' end describe 'with a constraint with options' do let(:options) { { key: 'value' } } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should pass with a positive expectation' end wrap_context 'when there are expected options' do let(:diff_matcher) do RSpec::SleepingKingStudios::Matchers::Core::DeepMatcher .new(expected_options) .tap { |matcher| matcher.matches?(actual.options) } end let(:failure_message) do "#{super()}, but the options do not match:\n" + tools.str.indent(diff_matcher.failure_message, 2) end describe 'with a constraint with missing options' do let(:options) { {} } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with changed options' do let(:options) { expected_options.merge(language: 'Basic') } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with added options' do let(:options) { expected_options.merge(compiler: 'gcc') } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with matching options' do let(:options) { expected_options } let(:actual) { Spec::ExampleConstraint.new(**options) } include_examples 'should pass with a positive expectation' end end end wrap_context 'when there are expected options' do let(:diff_matcher) do RSpec::SleepingKingStudios::Matchers::Core::DeepMatcher .new(expected_options) .tap { |matcher| matcher.matches?(actual.options) } end let(:failure_message) do "#{super()}, but the options do not match:\n" + tools.str.indent(diff_matcher.failure_message, 2) end describe 'with a constraint with missing options' do let(:options) { {} } let(:actual) { Stannum::Constraints::Base.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with changed options' do let(:options) { expected_options.merge(language: 'Basic') } let(:actual) { Stannum::Constraints::Base.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with added options' do let(:options) { expected_options.merge(compiler: 'gcc') } let(:actual) { Stannum::Constraints::Base.new(**options) } include_examples 'should fail with a positive expectation' end describe 'with a constraint with matching options' do let(:options) { expected_options } let(:actual) { Stannum::Constraints::Base.new(**options) } include_examples 'should pass with a positive expectation' end end end describe '#with_options' do let(:options) { { key: 'value' } } it 'should define the method' do expect(matcher) .to respond_to(:with_options) .with(0).arguments .and_any_keywords end it { expect(matcher.with_options).to be matcher } it 'should set the expected options' do expect { matcher.with_options(**options) } .to change(matcher, :expected_options) .to be == options end end end
class DropVideosTable < ActiveRecord::Migration[5.0] def change drop_table :videos end end
When /^I create a category titled "([^"]*)"$/ do |title| click_link "Manage Categories" click_link "New Item" fill_in "Title", :with => title click_button "Create Item" end When /^I have a category titled "([^"]*)"$/ do |title| @category = Category.create!(:title => title) end When /^I change the category title to "([^"]*)"$/ do |new_title| click_link "Manage Categories" within("#item_#{@category.id}") do click_link "Edit" end fill_in 'Title', :with => new_title click_button "Update Category" end Then /^The category title should be "([^"]*)"$/ do |category_name| page.should have_content(category_name) end When /^I delete the category$/ do click_link "Manage Categories" page.evaluate_script("window.alert = function(msg) { return true; }") page.evaluate_script("window.confirm = function(msg) { return true; }") within("#item_#{@category.id}") do click_link "Destroy" end end Then /^The category should be deleted$/ do page.should_not have_content(@category.title) end
class Public::CareerInterestsController < Public::BaseController before_filter :get_details def show end def create @career_interest = CareerInterest.new @career_interest.assign_attributes(permitted_params) @career_interest.source = :registration_desk save_resource(@career_interest) end def confirm unless @career_interest.confirm! flash[:error] = "Unknown error while confirming" end redirect_to public_event_career_interest_path(event_id: @event.slug, id: @career_interest.id) end private def get_details @event = Event.find_by_slug(params[:event_id]) || Event.find_by_id(params[:event_id]) @career_interest = CareerInterest.find_by_id(params[:id]) @fresher = @career_interest.candidate end def set_navs set_nav("public/events") end end
module Square # All configuration including auth info and base URI for the API access # are configured in this class. class Configuration < CoreLibrary::HttpClientConfiguration # The attribute readers for properties. attr_reader :environment, :custom_url, :access_token, :square_version, :user_agent_detail def additional_headers @additional_headers.clone end class << self attr_reader :environments end def initialize(connection: nil, adapter: :net_http_persistent, timeout: 60, max_retries: 0, retry_interval: 1, backoff_factor: 2, retry_statuses: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524], retry_methods: %i[get put], http_callback: nil, environment: 'production', custom_url: 'https://connect.squareup.com', access_token: '', square_version: '2023-08-16', user_agent_detail: '', additional_headers: {}) super connection: connection, adapter: adapter, timeout: timeout, max_retries: max_retries, retry_interval: retry_interval, backoff_factor: backoff_factor, retry_statuses: retry_statuses, retry_methods: retry_methods, http_callback: http_callback # Current API environment @environment = String(environment) # Sets the base URL requests are made to. Defaults to `https://connect.squareup.com` @custom_url = custom_url # The OAuth 2.0 Access Token to use for API requests. @access_token = access_token # Square Connect API versions @square_version = square_version # Additional headers to add to each API request @additional_headers = additional_headers.clone # The Http Client to use for making requests. set_http_client CoreLibrary::FaradayClient.new(self) # User agent detail, to be appended with user-agent header. @user_agent_detail = get_user_agent(user_agent_detail) end def clone_with(connection: nil, adapter: nil, timeout: nil, max_retries: nil, retry_interval: nil, backoff_factor: nil, retry_statuses: nil, retry_methods: nil, http_callback: nil, environment: nil, custom_url: nil, access_token: nil, square_version: nil, user_agent_detail: nil, additional_headers: nil) connection ||= self.connection adapter ||= self.adapter timeout ||= self.timeout max_retries ||= self.max_retries retry_interval ||= self.retry_interval backoff_factor ||= self.backoff_factor retry_statuses ||= self.retry_statuses retry_methods ||= self.retry_methods http_callback ||= self.http_callback environment ||= self.environment custom_url ||= self.custom_url access_token ||= self.access_token square_version ||= self.square_version user_agent_detail ||= self.user_agent_detail additional_headers ||= self.additional_headers Configuration.new(connection: connection, adapter: adapter, timeout: timeout, max_retries: max_retries, retry_interval: retry_interval, backoff_factor: backoff_factor, retry_statuses: retry_statuses, retry_methods: retry_methods, http_callback: http_callback, environment: environment, custom_url: custom_url, access_token: access_token, square_version: square_version, user_agent_detail: user_agent_detail, additional_headers: additional_headers) end def get_user_agent(user_agent_detail) raise ArgumentError, 'The length of user-agent detail should not exceed 128 characters.' unless user_agent_detail.length < 128 user_agent_detail end # All the environments the SDK can run in. ENVIRONMENTS = { 'production' => { 'default' => 'https://connect.squareup.com' }, 'sandbox' => { 'default' => 'https://connect.squareupsandbox.com' }, 'custom' => { 'default' => '{custom_url}' } }.freeze # Generates the appropriate base URI for the environment and the server. # @param [Configuration::Server] server The server enum for which the base URI is # required. # @return [String] The base URI. def get_base_uri(server = 'default') parameters = { 'custom_url' => { 'value' => custom_url, 'encode' => false } } APIHelper.append_url_with_template_parameters( ENVIRONMENTS[environment][server], parameters ) end end end
class AddPictureToHostel < ActiveRecord::Migration def change add_column :hostels, :picture, :string end end
class Admin::OfficersController < AdminController def index @mcc_officers = Officer.order('created_at asc').where(undergrad: true) @mice_officers = Officer.order('created_at asc').where(undergrad: false) end def edit @officer = Officer.find params[:id] end def update @officer = Officer.find params[:id] if @officer.update_attributes(params[:officer]) flash[:success] = 'Officer successfully updated.' else flash[:danger] = 'Something went wrong!' end redirect_to admin_officers_path end def new @officer = Officer.new end def create @officer = Officer.new params[:officer] if @officer.valid? @officer.save! flash[:success] = 'Officer successfully created.' else flash[:danger] = 'Something went wrong! Officer was not created.' end redirect_to admin_officers_path end def destroy @officer = Officer.find params[:id] @officer.destroy! flash[:success] = 'Officer deleted.' redirect_to admin_officers_path end end
# Copied and modified directly from /sprockets-2.1.2/lib/sprockets/server.rb module Sprockets module Server alias_method :_orig_headers, :headers def wrapped_headers(env, asset, length) output = _orig_headers(env, asset, length) # Ensure that font files have CORs headers if ['application/octet-stream', "image/svg+xml", "application/x-font-ttf", "application/x-font-truetype", "application/x-font-opentype", "application/x-font-woff" , "application/vnd.ms-fontobject"].include? asset.content_type output['Access-Control-Allow-Origin'] = '*' end output end alias_method :headers, :wrapped_headers end end
module Madmin module Generators class ResourceGenerator < Rails::Generators::NamedBase include Madmin::GeneratorHelpers source_root File.expand_path("../templates", __FILE__) def eager_load Rails.application.eager_load! end def generate_resource template "resource.rb", "app/madmin/resources/#{file_path}_resource.rb" end def generate_controller destination = Rails.root.join("app/controllers/madmin/#{file_path.pluralize}_controller.rb") template("controller.rb", destination) end def generate_route if route_namespace_exists? route "resources :#{plural_name}", namespace: class_path, indentation: separated_routes_file? ? 2 : 4, sentinel: /namespace :madmin do\s*\n/m else route "resources :#{plural_name}", namespace: [:madmin] + class_path end end private def associations model.reflections.reject { |name, association| # Hide these special associations name.starts_with?("rich_text") || name.ends_with?("_attachment") || name.ends_with?("_attachments") || name.ends_with?("_blob") || name.ends_with?("_blobs") }.keys end def attributes model.attribute_names + virtual_attributes - redundant_attributes end def virtual_attributes virtual = [] # has_secure_password columns password_attributes = model.attribute_types.keys.select { |k| k.ends_with?("_digest") }.map { |k| k.delete_suffix("_digest") } virtual += password_attributes.map { |attr| [attr, "#{attr}_confirmation"] }.flatten # Add virtual attributes for ActionText and ActiveStorage model.reflections.each do |name, association| if name.starts_with?("rich_text") virtual << name.split("rich_text_").last elsif name.ends_with?("_attachment") virtual << name.split("_attachment").first elsif name.ends_with?("_attachments") virtual << name.split("_attachments").first end end virtual end def redundant_attributes redundant = [] # has_secure_password columns redundant += model.attribute_types.keys.select { |k| k.ends_with?("_digest") } model.reflections.each do |name, association| if association.has_one? next elsif association.collection? next elsif association.polymorphic? redundant << "#{name}_id" redundant << "#{name}_type" elsif name.starts_with?("rich_text") redundant << name else # belongs to redundant << "#{name}_id" end end redundant end def model @model ||= class_name.constantize end def formatted_options_for_attribute(name) options = options_for_attribute(name) return if options.blank? ", " + options.map { |key, value| "#{key}: #{value}" }.join(", ") end def options_for_attribute(name) if %w[id created_at updated_at].include?(name) {form: false} # has_secure_passwords should only show on forms elsif name.ends_with?("_confirmation") || virtual_attributes.include?("#{name}_confirmation") {index: false, show: false} # Counter cache columns are typically not editable elsif name.ends_with?("_count") {form: false} # Attributes without a database column elsif !model.column_names.include?(name) {index: false} end end end end end
FactoryGirl.define do factory :entity do entity_type 1 title "President" name "Brown Web Design" address "123 Main" address2 "Ste O" city "Monroe" state "GA" zip "30655" end end
class CreateShippings < ActiveRecord::Migration[6.0] def change create_table :shippings do |t| t.string :fee_burden, null:false t.string :method, null: false t.string :prefecture_from, null:false t.string :period_before_shipping, null:false t.references :item, foreign_key: true t.timestamps end end end
class Machine class Plotter Point = Struct.new(:x, :y) attr_accessor :invert, :threshold, :run, :forward, :steps def initialize(machine:) @machine = machine @pen = machine.pen @bed = machine.bed @compiler= machine.compiler @invert = false @threshold = 90 @run = false @forward = true @steps = @machine.bed.width setup end def setup end def plot end def reset end # invert plotter color choices def invert_plotter @invert = !@invert end def threshold=int int = int.clamp(1, 255) @threshold = int end def steps=int int = int.clamp(1, (@bed.width*@bed.height).to_i) @steps = int end def pen_x @pen.x-@bed.x end def pen_y @pen.y-@bed.y end end end
module Api module V1 class UsersController < Api::V1::BaseController respond_to :json before_action :set_user, only: [:show, :update, :destroy] before_action :check_header before_action :validate_type, only: [:create, :update] #I don't think I need this one, for at least create #before_action :validate_user, only: [:create, :update, :destroy] def index if current_user.admin? @users = User.all render json: @users else render json: { message: "Access denied. You are not authorized to enter" } end end def show if @user == current_user || current_user.admin? render json: @user else render json: { message: "Access denied. You are not authorized to enter" } end end def create @user = User.new(user_params) if @user.save render json: @user, status: :created else render_error(@user, :unprocessable_entity) end end def update if @user.update_attributes(user_params) render json: @user, status: :ok else render_error(@user, :unprocessable_entity) end end def destroy @user.destroy head 204 end private def user_params ActiveModelSerializers::Deserialization.jsonapi_parse(params) end def set_user begin @user = User.find(params[:id]) rescue ActiveRecord::RecordNotFound user = User.new user.errors.add(:id, "Wrong ID provided") render_error(user, 404) and return end end def check_header if ['POST','PUT','PATCH'].include? request.method if request.content_type != "application/vnd.api+json" head 406 and return end end end def render_error(resource, status) render json: resource, status: status, adapter: :json_api, serializer: ActiveModel::Serializer::ErrorSerializer end def validate_type if params['data'] && params['data']['type'] if "api/v1/" + params['data']['type'] == params[:controller] return true end end head 409 and return end #def validate_user # token = request.headers["WWW-Authenticate"] # byebug # head 403 and return unless token # @user = User.find_by auth_token: token # head 403 and return unless @user #end end end end
require "rails_helper" RSpec.feature "User logs in with Google" do before do mock_auth_hash end context "they use valid login credentials" do scenario "they are redirected to the homepage" do visit '/' expect(page.status_code).to eq 200 click_link "Sign in with Google" expect(current_path).to eq "/" expect(page).to have_content "first" expect(page).to have_content "Logout" end end end
class AddOwnerIdToBuildings < ActiveRecord::Migration def change add_column :buildings, :owner_id, :integer add_index :buildings, :owner_id end end
# Please note, Robin Walker is used throughout these tests. This is the user # utilized by the Steam API docs to demonstrate functionality. class SteamServiceTest < ActiveSupport::TestCase TEST_USERNAME = "robinwalker".freeze TEST_STEAM_ID = "76561197960435530".freeze # The base happy path for retrieving all games test 'should retrieve the users full steam library' do VCR.use_cassette('steam_api_requests') do user = users(:one) profile = user SteamService.update_library_for(profile.steam_profile) user.reload game = user.steam_profile.library_entries.last.game assert user.steam_profile.library_entries.count == 652, "Not enough library entries read." assert game.name == 'Dota 2 Workshop Tools Alpha' assert game.icon_url == '' end end # Ensuring that recently played games show up as such # # Yes, I know the query is obtuse. This particular data will never be # needed in the actual application; so I choose instead to muddy up this # one test a bit. test 'should setup recently played games' do VCR.use_cassette('steam_api_requests') do user = users(:one) profile = user SteamService.update_library_for(profile.steam_profile) user.reload game = Game.where(appid: 400760).first assert user .steam_profile .library_entries .recent .where(game_id: game.id) .count > 0, "400760 wasn't found amongst the recent games." end end # The base happy path for retrieving a steam_id test 'should retrieve steam_id from vanity_name' do VCR.use_cassette('steam_api_requests') do steam_id = SteamService.steam_id_for(TEST_USERNAME) assert steam_id == TEST_STEAM_ID, 'Invalid steam id returned' end end end
require 'json' require 'google/apis/gmail_v1' require 'googleauth' require 'googleauth/stores/file_token_store' require 'fileutils' require 'gmail' require 'dotenv' class Mailing OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'.freeze APPLICATION_NAME = 'Gmail API Ruby Quickstart'.freeze CREDENTIALS_PATH = 'db/credentials.json'.freeze TOKEN_PATH = 'db/token.yaml'.freeze SCOPE = Google::Apis::GmailV1::AUTH_GMAIL_READONLY def authorize client_id = Google::Auth::ClientId.from_file(CREDENTIALS_PATH) token_store = Google::Auth::Stores::FileTokenStore.new(file: TOKEN_PATH) authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store) user_id = 'default' credentials = authorizer.get_credentials(user_id) if credentials.nil? url = authorizer.get_authorization_url(base_url: OOB_URI) puts 'Open the following URL in the browser and enter the ' \ "resulting code after authorization:\n" + url code = gets credentials = authorizer.get_and_store_credentials_from_code( user_id: user_id, code: code, base_url: OOB_URI ) end credentials end def perform # Initialize the API service = Google::Apis::GmailV1::GmailService.new service.client_options.application_name = APPLICATION_NAME service.authorization = authorize # Show the user's labels user_id = 'me' gmail = Gmail.connect!(ENV["account"],ENV["password"]) json=File.read("db/townhalls.json") obj=JSON.parse(json) obj.each do |k| if k["mail"] != "Pas de mail ='(" gmail.deliver do to "#{k["mail"]}" subject "Apprendre à coder, une nouvelle pédagogie" text_part do body "Bonjour, Je m'appelle William, je suis élève à The Hacking Project, une formation au code gratuite, sans locaux, sans sélection, sans restriction géographique. La pédagogie de notre école est celle du peer-learning, où nous travaillons par petits groupes sur des projets concrets qui font apprendre le code. Le projet du jour est d'envoyer (avec du codage) des emails aux mairies pour qu'ils nous aident à faire de The Hacking Project un nouveau format d'éducation pour tous. Déjà 500 personnes sont passées par The Hacking Project. Est-ce que la mairie de #{k["ville"]} veut changer le monde avec nous ? Charles, co-fondateur de The Hacking Project pourra répondre à toutes vos questions : 06.95.46.60.80" end end end end end end
require "spec_helper" RSpec.describe Card do let(:card) { Card.new("10", "♥")} let(:seven_spades) { Card.new("7","♠")} let(:ace_spades) { Card.new("A","♠") } describe "#initialze" do it "should create a card" do expect(card).to be_a(Card) expect(card.rank).to eq("7") expect(card.suit).to eq("♥") end end describe "#face_card?" do it "should return true for J, Q, K" do expect(jack_spades.face_card?).to be true expect(queen_diamonds.face_card?).to be true expect(king_hearts.face_card?).to be true end it "should return false for any other ranks" do expect(card.face_card?).to be false expect(ace_spades.face_card?).to be false end it "should return true for Aces" do expect(ace_spades.ace?).to be true end it "should return false for other ranks" do expect(card.ace?).to be false expect(king_clubs.ace?).to be false end end end
#!/usr/bin/env ruby require 'dogapi' require 'yaml' require 'json' require 'faraday' require_relative './lib' ##################################################################### require 'dogapi' require 'yaml' require 'sinatra' require 'thread' require 'uri' require 'json' class LoggerDog def initialize(dog) @dog = dog end def method_missing(meth, *args, &blk) # puts "sending: #{meth}, #{args.join(',')}" @dog.send(meth, *args, &blk) end end class FakeDog def initialize(*whatever) end def batch_metrics(&blk) blk.call end def emit_point(k,v, hsh={}) p({k: k, v: v, hsh: hsh}) end end config = YAML.load_file(ARGV[0]) datadog_api_key = config["datadog_api_key"] datadog = LoggerDog.new(Dogapi::Client.new(datadog_api_key)) name = config["name"] sleep 5.0 loop do conn = Faraday.new(:url => config["nats_monitor_uri"]) do |faraday| faraday.request :url_encoded # form-encode POST params faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end varz = Lib.new.flat_hash('nats_stress.nats_monitor.varz', JSON.parse(conn.get('/varz').body)) subscriptionsz = Lib.new.flat_hash('nats_stress.nats_monitor.subz', JSON.parse(conn.get('/subscriptionsz').body)) connz = JSON.parse(conn.get('/connz').body) datadog.batch_metrics do varz.each do |k,v| datadog.emit_point(k,v,host: name) end subscriptionsz.each do |k,v| datadog.emit_point(k,v,host: name) end # p connz conns = connz.delete('connections') # p conns connz_top = Lib.new.flat_hash('nats_stress.nats_monitor.conz', connz) connz_top.each do |k,v| datadog.emit_point(k,v,host: name) end conns.each do |conn| conn_flat = Lib.new.flat_hash('nats_stress.nats_monitor.conn', conn) conn_flat.each do |k,v| datadog.emit_point(k,v,host: name, tags: ["client:#{conn['ip']}"]) end end end sleep 0.95 end
FactoryBot.define do factory :station do sequence(:name) { |n| "station-#{n}"} sequence(:dock_count) { |n| "dock-#{n}"} city "San Fran" installation_date Date.today end end
Given(/^I'm on the Documents page$/) do click_link "Documents" end When (/^I click Upload to take me to the upload page$/) do first(:link, "Upload").click end When (/^I click New Folder$/) do first(:link, "New Folder").click end When(/^I fill in the folder name and submit$/) do fill_in 'folder_name', :with => "new_folder" click_button "Create Folder" end Then(/^A new folder will get created$/) do assert page.has_content?("new_folder") end When(/^I attach and upload a file$/) do attach_file('asset_uploaded_file', File.absolute_path('./public/bg.jpg')) click_button "Upload" end Then(/^The file can be seen by the user$/) do assert page.has_content?("bg.jpg") end When(/^I click Delete$/) do first(:link, "Delete").click end Then(/^I will see a Successful delete message$/) do assert page.has_content?("Successfully deleted") end Then(/^I click Download$/) do first(:link, "Download").click end Then(/^I click the folder name$/) do first(:link, "new_folde").click end Then(/^I should have navigated into the folder$/) do assert page.has_content?("» new_folder") end
# # guest_section.rb # ConstantContact # # Copyright (c) 2013 Constant Contact. All rights reserved. module ConstantContact module Components module EventSpot class GuestSection < Component attr_accessor :label, :fields # Factory method to create a GuestSection object from a hash # @param [Hash] props - hash of properties to create object from # @return [GuestSection] def self.create(props) obj = GuestSection.new props.each do |key, value| key = key.to_s if key == 'fields' value ||= [] obj.fields = value.collect do |field| Components::EventSpot::RegistrantField.create(field) end else obj.send("#{key}=", value) if obj.respond_to? key end end if props obj end end end end end
class Controldepagogt < ApplicationRecord validates :tipojugada, :limitexticket, :limiteglobal, presence: { message: "No puede estar en Blanco. Favor completar." } validates :limitexticket, :limiteglobal, numericality: { only_integer: true } end
module PaintingsHelper def new_form? @painting.new_record? end def form_title new_form? ? "New Painting" : "Edit Painting" end def form_info_text action = new_form? ? "create a new" : "edit this" text = "Use the following form to #{action} painting." content_tag(:p,text) end end
require 'rails_helper' RSpec.describe "#pet_id_lookup", type: :feature do it 'can find a pet object from an id' do shelter_1 = Shelter.create( name: "Henry Porter's Puppies", address: "1315 Monaco Parkway", city: "Denver", state: "CO", zip: "80220") pet_1 = Pet.create( name: "Holly", age: 4, sex: "Male", shelter_id: shelter_1.id, image: 'hp.jpg', description: 'Cute', adoptable_status: 'Adoptable') visit '/shelters' ac = ApplicationController.new expect(ac.pet_id_lookup(pet_1.id)).to eq(pet_1) end end
class CreateClassshipInvites < ActiveRecord::Migration def self.up create_table :classship_invites do |t| t.integer :classship_want_id t.integer :user_id t.integer :invite_user_id t.boolean :email_flag t.boolean :read_flag t.timestamps end end def self.down drop_table :classship_invites end end
require './lib/cfiber/version' Gem::Specification.new do |s| s.name = "cfiber" s.author = "Jean-Denis Vauguet <jd@vauguet.fr>" s.email = "jd@vauguet.fr" s.homepage = "http://www.github.com/chikamichi/cfiber" s.summary = "Ruby Fibers using Ruby Continuations" s.description = "Continuations used to implement Fibers as provided by Ruby 1.9. Works in 1.8 as well." s.files = Dir["lib/**/*"] + ["MIT-LICENSE", "README.md", "CHANGELOG.md"] s.version = CFiber::VERSION s.add_development_dependency 'logg' end
class RemoveRowOrderAndSectionFromQuestion < ActiveRecord::Migration def change remove_column :questions, :section_id remove_column :questions, :row_order end end
require 'rails_helper' describe IdentificationsController do let(:user) { create(:user) } describe "#index" do context 'log in' do before do login user get :index end context 'address existence' do let(:user_address) { create(:address, user_id: user.id) } it 'renders the :index template' do expect(response).to render_template :index end end context 'address not existence' do it 'assigns @address' do expect(assigns(:address)).to be_a_new(Address) end it 'renders the :index template' do expect(response).to render_template :index end end end context 'not log in' do before do get :index end it 'redirects to new_user_session_path' do expect(response).to redirect_to(new_user_session_path) end end end describe "#create" do context 'log in' do before do login user end context 'can save' do let(:params) do { address: { user_id: user.id, postal_code: Faker::Number.number(digits: 7), prefecture: Gimei.prefecture.kanji , city: Gimei.city.kanji, street: Gimei.town.kanji, building_name: Gimei.last.kanji, phone: Faker::Number.number(digits: 11) } } end subject { post :create, params: params } it 'count up address' do expect{ subject }.to change(Address, :count).by(1) end it 'redirects to identifications_path' do subject expect(response).to redirect_to(identifications_path) end end context 'can not save' do let(:invalid_params) do { address: { user_id: user.id, postal_code: "12345678", prefecture: Gimei.prefecture.kanji , city: Gimei.city.kanji, street: Gimei.town.kanji, building_name: Gimei.last.kanji, phone: Faker::Number.number(digits: 11) } } end subject { post :create, params: invalid_params } it 'not count up address' do expect{ subject }.to change(Address, :count).by(0) end it 'renders index' do subject expect(response).to render_template :index end end end context 'not log in' do before do post :create end it 'redirects to new_user_session_path' do expect(response).to redirect_to(new_user_session_path) end end end describe "#update" do let(:address) { create(:address, user_id: user.id)} context 'log in' do before do login user end context 'can update' do let(:params) do { address: { user_id: address.user_id, postal_code: "7777777", prefecture: address.prefecture, city: address.city, street: address.street, building_name: address.building_name, phone: address.phone, }, id: address.id } end subject { patch :update, params: params} it 'update column' do subject expect(address.reload.postal_code).to eq "7777777" end it 'redirects to identifications_path' do subject expect(response).to redirect_to(identifications_path) end end context 'can not update' do let(:params) do { address: { user_id: address.user_id, postal_code: "88888888", prefecture: address.prefecture, city: address.city, street: address.street, building_name: address.building_name, phone: address.phone, }, id: address.id } end subject { patch :update, params: params} it 'not update column' do subject expect(address.reload.postal_code).not_to eq "88888888" end it 'renders the :edit template' do subject expect(response).to render_template :index end end end context 'not log in' do before do patch :update, params: { id: address.id } end it 'redirects to new_user_session_path' do expect(response).to redirect_to(new_user_session_path) end end end end
FactoryBot.define do factory :delivery_address do delivery_family_name {"田中"} delivery_first_name {"花子"} delivery_family_name_kana {"タナカ"} delivery_first_name_kana {"ハナコ"} post_code {"1234567"} prefecture_id {"id: 1, name: '北海道'"} city {"札幌"} home_number {"1-1-1"} building_name {"山田ビル101"} phone_number {"09012345678"} association :user end end
class Migrationname < ActiveRecord::Migration def change remove_column :games, :cover_image end end
module Harvest module HTTP module Server module Resources class UsernameResource < Resource def content_types_provided [['application/json', :to_json]] end def allowed_methods %W[ GET ] end def resource { status: username_text_status } end def to_json resource.to_json end private def username_text_status if user_service.username_available?(request_username) "available" else "unavailable" end end def user_service harvest_app.application_services[:user_service] end def request_username request.path_info[:username] end end end end end end
# KeyValue linked list for hashtable implementation Node = Struct.new(:key, :value, :next) # KeyValue LinkedList for HashTable # Doesn't enforce unique contents, can have duplicate keys class LinkedList include Enumerable attr_reader :length def initialize @head = nil @length = 0 end def each current = @head while current != nil do yield current current = current.next end end def get(key) node = self.find { |n| n.key == key} if node return node.value else return nil end end def insert_or_update(key, value) node = self.find { |n| n.key == key} if node node.value = value else insert(key, value) end end def insert_at_head(key, value) if @head == nil @head = Node.new(key, value) else @head = Node.new(key, value, @head) end @length += 1 end alias_method :insert, :insert_at_head def remove(key) current = @head while current != nil do if current.key == key # gonna delete if @head == current @head = current.next else n = current.next current.key = n.key current.value = n.value current.next = n.next #free n? end end current = current.next end end end
class Comment < ApplicationRecord belongs_to :creator, class_name: "User", foreign_key: :creator_id belongs_to :card end
require 'spec_helper_acceptance' describe 'gitea class' do context 'with default parameters' do # Using puppet_apply as a helper it 'works idempotently with no errors' do pp = <<-PUPPET class { 'gitea': } PUPPET # Run it twice and test for idempotency apply_manifest(pp, catch_failures: true) apply_manifest(pp, catch_changes: true) end describe group('git') do it { is_expected.to exist } end describe user('git') do it { is_expected.to exist } end describe file('/opt/gitea') do it { is_expected.to be_directory } end describe file('/opt/gitea/custom') do it { is_expected.to be_directory } end describe file('/opt/gitea/custom/conf') do it { is_expected.to be_directory } end describe file('/opt/gitea/custom/conf/app.ini') do it { is_expected.to be_file } end describe file('/opt/gitea/data') do it { is_expected.to be_directory } end describe file('/opt/gitea/data/attachments') do it { is_expected.to be_directory } end describe file('/var/log/gitea') do it { is_expected.to be_directory } end describe file('/opt/gitea/gitea') do it { is_expected.to be_file } end describe file('/var/git') do it { is_expected.to be_directory } end describe file('/lib/systemd/system/gitea.service') do it { is_expected.to be_file } end describe port(3000) do it { is_expected.to be_listening } end end end
class Backend::BaseController < ApplicationController before_filter :authenticate_user! def index @locations = Location.pluck(:id, :name) @categories = Category.pluck(:id, :name) end end
class CommentsController < ApplicationController before_action :comment_params, only: [:create, :update, :delete] def index @comments = Comment.all.order(id: :desc) end def new @comment = Comment.new end def create binding.pry @comment = Comment.new(comment_params) if @comment.save redirect_to comments_path, flash: {success: "Create successfull"} else render :new, flash: {error: "Generate with errors"} end end def edit @comment = Comment.find_by(id: params[:id]) end def destroy @comment = Comment.find_by(id: params[:id]) end def update @comment = Comment.find_by(id: params[:id]) if @comment.update(comment_params) redirect_to comment_path(@comment) else render :edit end end def show @comment = Comment.find_by(id: params[:id]) end private def comment_params params.require(:comment).permit(:name, :email) end end
FactoryBot.define do factory :location do name { Faker::LordOfTheRings.location } external_id { Faker::Code.nric } secret_code { Faker::Address.zip } end end
# frozen_string_literal: true class StationWorker include Sidekiq::Worker sidekiq_options retry: false def perform Station.update_all_stations end end
# frozen_string_literal: true module Eq module Users # Eq::Users::UserRepository class UserRepository < RepositoryBase def load_by_email(email) map_record(orm_adapter.find_by(email: email)) end private def orm_adapter ::User end def map_record(record) user_entity_factory.build(record) end def user_entity_factory @user_entity_factory ||= EqTcm::Container['eq.users.user_entity_factory'] end end end end
require 'spec_helper' require "capybara/rails" describe "xml_file_downloads/show.html.erb" do describe "ApplicationHelper" do before :each do shop = Shop.create({:name => "alza.sk", :url => "Http://www.alza.sk"}) XmlFileDownload.create(:shop => shop, :url => "http://www.sme.sk/index.html", :path => "/tmp/1.html") XmlFileDownload.create(:shop => shop, :url => "http://www.google.sk/index.html", :path => "/dev/null") XmlFileDownload.create(:shop => shop, :url => "http://www.yahoo.com/index.html", :path => "/tmp/2.html") end it "should render index page" do visit '/xml_file_downloads' # Run the generator again with the --webrat flag if you want to use webrat matchers find(:xpath, "//table/tr[2]").should have_content("http://www.sme.sk/index.html") find(:xpath, "//table/tr[2]").should have_content("enqueued") find(:xpath, "//table/tr[2]").should have_content("/tmp/1.html") find(:xpath, "//table/tr[2]").should have_link("Show") find(:xpath, "//table/tr[2]").should have_link("Destroy") find(:xpath, "//table/tr[3]").should have_content("http://www.google.sk/index.html") find(:xpath, "//table/tr[3]").should have_content("enqueued") find(:xpath, "//table/tr[3]").should have_content("/dev/null") find(:xpath, "//table/tr[4]").should have_content("http://www.yahoo.com/index.html") find(:xpath, "//table/tr[4]").should have_content("enqueued") find(:xpath, "//table/tr[4]").should have_content("/tmp/2.html") #save_and_open_page end it "should order by url" do visit '/xml_file_downloads' click_link "url" find(:xpath, "//table/tr[2]").should have_content("http://www.google.sk/index.html") find(:xpath, "//table/tr[3]").should have_content("http://www.sme.sk/index.html") find(:xpath, "//table/tr[4]").should have_content("http://www.yahoo.com/index.html") end it "should filter" do visit '/xml_file_downloads' fill_in "search_url_contains",:with => ".sk" click_button "filter" find(:xpath, "//table/tr[2]").should have_content("http://www.sme.sk/index.html") find(:xpath, "//table/tr[3]").should have_content("http://www.google.sk/index.html") end it "can skip filter form" do visit '/xml_feed_handlers' page.should_not have_xpath("/html/body/form/table/tbody/tr/td[3]//input") end it "can add class to <td>" do visit '/xml_feed_handlers' page.should have_xpath("//td[@class='result']") end describe "different forms of input" do it "provide select box" do visit '/xml_feed_handlers' page.should have_xpath("//select") end it "provide textbox" do visit '/xml_file_downloads' page.should have_xpath("//input[@type='text']") end end end end
# ========================================================================== # Project: Lebowski Framework - The SproutCore Test Automation Framework # License: Licensed under MIT license (see License.txt) # ========================================================================== module Lebowski module Foundation module Mixins # # Mixin provides support to any view that will act as a list item view # for a list view. # module ListItemViewSupport include CollectionItemViewSupport def can_drag_before?() return true end def can_drag_after?() return true end def apply_drag_before(source) params = { :mouse_offset_x => :center, :mouse_offset_y => :center } source.drag_to self, (self.width / 2).floor, 2, params end def apply_drag_after(source) params = { :mouse_offset_x => :center, :mouse_offset_y => :center } source.drag_to self, (self.width / 2).floor, row_height, params end def row_height() return @parent["rowHeightForContentIndex.#{index}"] end end end end end
class CreateArticleListings < ActiveRecord::Migration def change create_table :article_listings do |t| t.integer :article_id t.string :mls_id t.timestamps end add_index :article_listings, :mls_id end end
require 'rails_helper' require 'dummy_opener' RSpec.describe Nordnet::Parser do let(:parser) { described_class.new(DummyOpener.new) } let(:good_call) { parser.call('test') } let(:attributes) {StockDatum::ATTRIBUTES} it 'returns a StockDatum' do expect(good_call).to be_a(StockDatum) end it 'returns a full StockDatum' do res = good_call attributes.each do |attribute| expect(res.public_send(attribute)).to_not be_nil end end context 'url_to_identifier' do let(:good_url) { 'https://www.nordnet.se/mux/web/marknaden/aktiehemsidan/index.html?identifier=101&marketid=11' } it 'it can find the identifier in a correct url' do expect(described_class.url_to_identifier(good_url)).to eq('101') end end end
# frozen_string_literal: true require 'spec_helper' RSpec.describe Motoko::Node do subject(:node) do described_class.new({ sender: 'example.com', data: { facts: { 'netwoking' => { 'interfaces' => { 'lo0' => { 'bindings' => [ 'address' => '127.0.0.1', 'netmask' => '255.0.0.0', 'network' => '127.0.0.0' ] } }, }, 'osfamily' => 'FreeBSD', 'os' => { 'family' => 'FreeBSD', } }, classes: [], agents: [], } }) end describe '#fact' do subject do node.fact(fact) end context 'with an existing fact' do let(:fact) { 'osfamily' } it { is_expected.to eq('FreeBSD') } end context 'with an existing dotted notation fact' do let(:fact) { 'os.family' } it { is_expected.to eq('FreeBSD') } end context 'with a non-existing fact' do let(:fact) { 'foo' } it { is_expected.to be_nil } end context 'with a non-existing dotted notation fact' do let(:fact) { 'foo.bar.baz' } it { is_expected.to be_nil } end context 'when traversing an array' do context 'with an existing dotted notation fact' do let(:fact) { 'netwoking.interfaces.lo0.bindings.0.address' } it { is_expected.to eq('127.0.0.1') } end context 'with a non-existing dotted notation fact' do let(:fact) { 'netwoking.interfaces.lo0.bindings.1.address' } it { is_expected.to be_nil } end end end end
class ChangeUrlsTableName < ActiveRecord::Migration def change rename_table("short_urls","short_url") end end
Rails.application.routes.draw do get 'static/page' root to: 'static#page' post "/subscribe" => "subscriptions#create" post "/push" => "push_notifications#create" # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
# auth for specific link helpers do def protected! return if authorized? headers['WWW-Authenticate'] = 'Basic realm="Restricted Area"' halt 401, message_for_no_auth_user end def message_for_no_auth_user a = Messages.where(link: "#{params[:link]}") @message = a[0].message erb :show end def authorized? @auth ||= Rack::Auth::Basic::Request.new(request.env) @auth.provided? and @auth.basic? and @auth.credentials and @auth.credentials == ['admin', 'password'] end end #auth for everything # use Rack::Auth::Basic, "Restricted Area" do |username, password| # username == 'admin' and password == 'admin' # end
class RenameYearIdInStudents < ActiveRecord::Migration def change rename_column :students, :year_id, :class_year_id end end
# == Schema Information # # Table name: supports # # id :integer not null, primary key # description :text # email :string # name :string # status :string default("Новый") # subject :string # created_at :datetime not null # updated_at :datetime not null # user_id :integer # # Indexes # # index_supports_on_user_id (user_id) # require 'rails_helper' describe Support do it "is invalid without a factory email" do support = build(:support, email: nil) support.valid? expect(support.errors[:email]).to include("can't be blank") end it "is invalid without a factory name" do support = build(:support, name: nil) support.valid? expect(support.errors[:name]).to include("can't be blank") end it "is invalid without a factory subject" do support = build(:support, subject: nil) support.valid? expect(support.errors[:subject]).to include("can't be blank") end it "is invalid without a factory description" do support = build(:support, description: nil) support.valid? expect(support.errors[:description]).to include("can't be blank") end it "has a valid factory" do expect(build(:support)).to be_valid end end
class Supplier < ActiveRecord::Base validates :name, presence: true belongs_to :user def self.csv_template headers = ["名称","締め条件","支払条件","銀行名"] csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv| csv << [] end csv_data.encode(Encoding::SJIS) end def self.to_download headers = %w(支払先 締め日 支払日 支払口座) csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv| all.each do |row| csv_column_values = [ row.name, row.close_condition, row.pay_condition, row.bank ] csv << csv_column_values end end csv_data.encode(Encoding::SJIS) end def self.admin_download headers = %w(ID user_id 支払先 締め日 支払日 支払口座) csv_data = CSV.generate(headers: headers, write_headers: true, force_quotes: true) do |csv| all.each do |row| csv_column_values = [ row.id, row.user_id, row.name, row.close_condition, row.pay_condition, row.bank ] csv << csv_column_values end end csv_data.encode(Encoding::SJIS) end end
class RemoveUidFromEmails < ActiveRecord::Migration def up remove_column :emails, :uid end def down add_column :emails, :uid, :integer end end
# encoding: UTF-8 # Copyright 2011-2013 innoQ Deutschland GmbH # # 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. require File.join(File.expand_path(File.dirname(__FILE__)), '../test_helper') class NoteTest < ActiveSupport::TestCase test 'should parse turtle note annotations' do str = '[umt:source <aDisBMS>; umt:thsisn "00000001"; dct:date "2010-04-29"]' concept = Concept::SKOS::Base.create(origin: '_00000001', published_at: Time.now) concept.note_skos_change_notes << ::Note::SKOS::ChangeNote.new.from_annotation_list!(str) assert_equal 1, Note::SKOS::ChangeNote.count, 1 assert_equal 3, Note::SKOS::ChangeNote.first.annotations.count, 3 assert_equal 1, Note::Annotated::Base.where(namespace: 'umt', predicate: 'thsisn', value: '"00000001"').count end end
require_relative 'principal.rb' # Document Filter class DocumentFilter def self.filter_author_signer(documents, principal) indexes = [] documents.each_index do |index| doc_md = documents.at(index).metadata if doc_md.author == principal || doc_md.signers.include?(principal) indexes.push(index) end end indexes end def self.filter_author(documents, principal) indexes = [] documents.each_index do |index| next unless author?(documents.at(index), principal) indexes.push(index) end indexes end def self.author?(document, principal) !document.w_reg? && principal == document.metadata.author end end
require 'spec_helper' describe Fortune do describe "#random" do specify{ subject.should respond_to(:message) } specify{ subject.should respond_to(:category) } before(:each) do Fortune.create(:message => "m1", :category => "a") Fortune.create(:message => "m2", :category => "b") Fortune.create(:message => "m3", :category => "c") Fortune.create(:message => "m4", :category => "d") Fortune.create(:message => "m5", :category => "e") end it "returns a random fortune" do fortunes = (1..5).map{|n| Fortune.random } fortunes.uniq.should have_at_least(3).items end end end
require_relative "figure-text.rb" describe "Figure Text Tool" do context "making triangle text with size 1" do it "#" do expect(triangle_text(1)).to eql("#") end end context "making triangle text with size 2" do it "# \n" + "##" do expect(triangle_text(2)).to eql("# \n" + "##") end end context "making triangle text with size 3" do it "# \n" + "## \n" + "###" do expect(triangle_text(3)).to eql("# \n" + "## \n" + "###") end end context "making half diamond text with size 1" do it "#" do expect(half_diamond_text(1)).to eql("#") end end context "making half diamond text with size 2" do it "# \n" + "##\n" + "# " do expect(half_diamond_text(2)).to eql("# \n" + "##\n" + "# ") end end context "making half diamond text with size 3" do it "# \n" + "## \n" + "###\n" + "## \n" + "# " do expect(half_diamond_text(3)).to eql("# \n" + "## \n" + "###\n" + "## \n" + "# ") end end context "making diamond text with size 1" do it "#" do expect(diamond_text(1)).to eql("#") end end context "making diamond text with size 2" do it " # \n" + "###\n" + " # " do expect(diamond_text(2)).to eql(" # \n" + "###\n" + " # ") end end context "making diamond text with size 3" do it " # \n" + " ### \n" + "#####\n" + " ### \n" + " # " do expect(diamond_text(3)).to eql(" # \n" + " ### \n" + "#####\n" + " ### \n" + " # ") end end context "making board text with size 1" do it "#" do expect(board_text(1)).to eql("#") end end context "making board text with size 2" do it "# \n" + " #" do expect(board_text(2)).to eql("# \n" + " #") end end context "making board text with size 3" do it "# #\n" + " # \n" + "# #" do expect(board_text(3)).to eql("# #\n" + " # \n" + "# #") end end context "making board text with size 4" do it "# # \n" + " # #\n" + "# # \n" + " # #" do expect(board_text(4)).to eql("# # \n" + " # #\n" + "# # \n" + " # #") end end end
module ActiveSupport #:nodoc: class TimeWithZone #:nodoc: def next_week_starting_on(day) beginning_of_week_starting_on(day).advance(:weeks => 1).change(:hour => 0) end def beginning_of_week_starting_on(day) days_to_week_start_day = (self.wday > day) ? (self.wday - day) : 7 - (day - self.wday) (self - days_to_week_start_day.days).midnight end def end_of_week_starting_on(day) days_to_week_end_day = (self.wday >= day) ? 6 - (self.wday - day) : (day - self.wday) - 1 (self + days_to_week_end_day.days).end_of_day end end end
class PatientsController < ApplicationController before_action :authenticate_user! before_action :set_patient, only: [ :show, :edit, :update ] load_and_authorize_resource def show @pulmonary_appointments = @patient.pulmonary_appointments.includes(:prescribed_inhalers) @tiss_evaluations = @patient.tiss_evaluations end def npsonho @patient = Patient.find_by(npsonho: params[:processo]) if @patient === nil @patient = Patient.new( name: params[:nome], rnu: params[:rnu], npsonho: params[:processo] ) render(:new) else @tiss_evaluations = @patient.tiss_evaluations @pulmonary_appointments = @patient.pulmonary_appointments render(:show) end end def index @q = Patient.ransack(params[:q]) @patients = @q.result(distinct: true).order(:name).paginate(page: params[:page]) end def new @patient = Patient.new end def create @patient = Patient.new(patient_params) if @patient.save flash[:success] = "#{ t('new-form-saved-flash') }." redirect_to(@patient) else render(:new) end end def edit end def update if @patient.update_attributes(patient_params) flash[:success] = "#{ t('edit-form-saved-flash') }" redirect_to(@patient) else render(:edit) end end private def patient_params params.require(:patient).permit( :name, :date_of_birth, :rnu, :npsonho ) end def set_patient @patient = Patient.find(params[:id]) end end
class Vanagon module Utilities module ShellUtilities module_function # join a combination of strings and arrays of strings into a single command # joined with '&&' # # @param commands [Array<String, Array<String>>] # @return [String] def andand(*commands) cmdjoin(commands, " && ") end # join a combination of strings and arrays of strings into a single command # joined with '&&' and broken up with newlines after each '&&' # # @param commands [Array<String, Array<String>>] # @return [String] def andand_multiline(*commands) cmdjoin(commands, " && \\\n") end def cmdjoin(commands, sep) commands.map { |o| Array(o) }.flatten.join(sep) end end end end
class ApplicationController < ActionController::Base include ApplicationPermissions # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_action do @notifications = current_user.notifications.order(created_at: :desc).load if user_signed_in? end after_action :track_user protected def require_login redirect_back(fallback_location: root_path) unless user_signed_in? end def track_user return unless user_signed_in? ip = request.remote_ip # Track ip address changes return unless session[:ip] != ip User::Log.log_user!(current_user, ip) session[:ip] = ip end end
require "#{RAILS_ROOT}/config/environment" # require 'fastercsv' require 'ar-extensions' namespace :localeze do namespace :shared do LOCALEZE_DATA_DIR = "#{RAILS_ROOT}/vendor/plugins/localeze/data" # Task Import: # - works fine desc "Import localeze categories" task :import_categories do klass = Localeze::Category columns = [:id, :name] file = "#{LOCALEZE_DATA_DIR}/categories.txt" options = { :validate => false } # truncate table klass.delete_all puts "#{Time.now}: importing file #{file}, starting with #{klass.count} objects" FasterCSV.foreach(file, :row_sep => "\r\n", :col_sep => '|') do |row| klass.import columns, [row], options end puts "#{Time.now}: completed, ended with #{klass.count} objects" end # Task Import: # * failed with 'illegal quote' error desc "Import localeze chains" task :import_chains do klass = Localeze::Chain columns = [:id, :name] file = "#{LOCALEZE_DATA_DIR}/chains.txt" options = { :validate => false } # truncate table klass.delete_all puts "#{Time.now}: importing file #{file}, starting with #{klass.count} objects" FasterCSV.foreach(file, :row_sep => "\r\n", :col_sep => '|') do |row| klass.import columns, [row], options end puts "#{Time.now}: completed, ended with #{klass.count} objects" end end # shared end # localeze
class Dock attr_reader :name, :max_rental_time, :rental_log, :revenue def initialize(name, max_rental_time) @name = name @max_rental_time = max_rental_time @rental_log ={} @revenue = 0 end def rent(boat, renter) if boat.returned? boat.go_out @rental_log[boat] = renter end end def charge(boat) card = @rental_log[boat].credit_card_number if boat.hours_rented <= @max_rental_time boat_cost = boat.price_per_hour * boat.hours_rented else boat_cost = boat.price_per_hour * @max_rental_time end {card_number: card, amount: boat_cost} end def log_hour @rental_log.each_key{|boat| boat.add_hour if !boat.returned?} end def return(boat) boat.come_back @revenue += charge(boat)[:amount] end end
require 'redis' module LogStreamer module Cache # Cache Redis implementation class Redis < BaseStreamer def initialize(params) @redis = ::Redis.new url: params[:addr] super params end def check_connections @redis.info end def write(values) key = key_schema(values) @redis.zadd(key, values[:time], marshal(values)) @redis.expire(key, @params[:cache_ttl]) @redis.zremrangebyscore(key, '-inf', Time.now.to_i - @params[:cache_ttl] - 1) end def read(filter, last_id, last_time, limit) key = key_schema(filter) # return last <limit> records if continuation is not provided return @redis.zrange(key, -limit, -1).map { |r| unmarshal(r) } unless last_time # should get all records of same time same_time_records = @redis.zrangebyscore(key, last_time, last_time) # and just next <limit> records next_time_records = @redis.zrangebyscore(key, last_time + 1, '+inf', limit: [0, limit]) all_records = (same_time_records + next_time_records).map { |r| unmarshal(r) } res = [] found = false all_records.each do |record| if record['id'] == last_id found = true else next unless found res << record end end # if something goes wrong res = all_records unless found res[0...limit] end private def marshal(values) values[:id] + '@' + values.to_json end def unmarshal(str) JSON.parse(str.split('@', 2)[1]) end end end end
if defined?(ChefSpec) def install_rbenv_plugin(name) ChefSpec::Matchers::ResourceMatcher.new(:rbenv_plugin, :install, name) end def run_rbenv_script(name) ChefSpec::Matchers::ResourceMatcher.new(:rbenv_script, :run, name) end end
class Severity < ActiveRecord::Base has_many :dataset_implementation_issues validates_presence_of :name, :description def self.yellow_rules # Returns an english description for how a dataset impolementation would be colored yellow on the overview/status dashboard thingy. ret = [] self.find(:all, :conditions => ["yellow_limit > 0"], :order => "sort_order DESC").each do |y| # puts("Inspecting #{y.name}--yellow limit is #{y.yellow_limit}, red is #{y.red_limit}.") # how much distance between yellow and red? # if just one, just say the yellow_limit number--no "or more" # if two, list both numbers between "or" # if > 2, list "between #yellow_limit and #red_limit" s = case y.red_limit - y.yellow_limit when 1 "#{y.yellow_limit}" when 2 "#{y.yellow_limt} or #{y.red_limit}" else "Between #{y.yellow_limit} and #{y.red_limit}" end ret << s + " open issues of '#{y.name}' severity, OR" end eat_last_or(ret) end def self.red_rules ret = [] self.find(:all, :conditions => ["red_limit > 0"], :order => "sort_order DESC").each do |r| ret << "#{r.red_limit} or more open issues of '#{r.name}' severity, OR" end eat_last_or(ret) end private def self.eat_last_or(arr) arr[-1].gsub!(", OR", ".") if arr[-1] arr end end
class VimCommandController < ApplicationController def index lang = params[:lang].presence || 'jp' @vim_commands = VimCommand.where(language: lang) end end
class Recruiter::RequirementsController < Recruiter::ApplicationController before_action :set_requirement, only: [:show, :edit, :update, :destroy, :send_requirements] layout "recruiter" def index @requirements = Requirement.only_sent_requirements.order(created_at: :asc) end def show @compulsory_requirement = @requirement.compulsory_requirement end private def set_requirement @requirement = Requirement.find(params[:id]) rescue ActiveRecord::RecordNotFound flash[:error] = "oopss something went wrong" redirect_to recruiter_dashboard_url end def set_company @company = Company.find(current_company.id) rescue ActiveRecord::RecordNotFound flash[:error] = "oopss something went wrong" redirect_to recruiter_dashboard_url end def requirement_params params.require(:requirement).permit(:title, :job_type, :location, :experience, :min_salary, :max_salary, :number_of_vacancies, :note, :company_id, :qualification_names, :skill_names, :qualification_ids => [], :skill_ids => []) end end
module BulkTimeEntriesHelper def grouped_options_for_issues(issues, selected, user=nil) closed_issues, open_issues = *issues.partition {|issue| issue.closed?} user ||= User.current html = '<option></option>' html << labeled_option_group_from_collection_for_select(l(:label_open_issues_plural), open_issues, selected, true, user) html << labeled_option_group_from_collection_for_select(l(:label_closed_issues_plural), closed_issues, selected, true, user) html end def labeled_option_group_from_collection_for_select(label, collection, selected, mygroup, user=nil) user ||= User.current html = '' if collection.any? html << "<optgroup label='#{label}'>" # debugger if mygroup my_collection, other_collection = *collection.partition {|issue| issue.assigned_to == user} html << labeled_option_group_from_collection_for_select("&nbsp;&nbsp;#{l(:label_my_issues_plural)}", my_collection, selected, false) html << labeled_option_group_from_collection_for_select("&nbsp;&nbsp;#{l(:label_other_issues_plural)}", other_collection, selected, false) else html << options_from_collection_for_select(collection, :id, :to_s, selected) end html << "</optgroup>" end html end def delete_unsafe_combobox_attribute(attributes) return if attributes.blank? attributes.delete_if{|k,v| k =~ Regexp.new(/^.*_new_value$/) } end end
# == Schema Information # # Table name: episodes # # id :integer not null, primary key # season :integer # episode_number :integer # title :string # airdate :datetime # show_id :integer # class EpisodeSerializer < ActiveModel::Serializer attributes :id, :title, :season, :episode_number, :airdate end
SS::Application.routes.draw do Opendata::Initializer concern :deletion do get :delete, on: :member end concern :workflow do post :request_update, on: :member post :approve_update, on: :member post :remand_update, on: :member get :approver_setting, on: :member post :approver_setting, on: :member get :wizard, on: :member post :wizard, on: :member end content "opendata" do get "/" => "main#index", as: :main resources :licenses, concerns: :deletion resources :sparqls, concerns: :deletion resources :apis, concerns: :deletion resources :members, only: [:index] namespace "workflow" do resources :idea_comments, concerns: :workflow end end node "opendata" do get "category/" => "public#index", cell: "nodes/category" get "area/" => "public#index", cell: "nodes/area" get "sparql/(*path)" => "public#index", cell: "nodes/sparql" post "sparql/(*path)" => "public#index", cell: "nodes/sparql" get "api/package_list" => "public#package_list", cell: "nodes/api" get "api/group_list" => "public#group_list", cell: "nodes/api" get "api/tag_list" => "public#tag_list", cell: "nodes/api" get "api/package_show" => "public#package_show", cell: "nodes/api" get "api/tag_show" => "public#tag_show", cell: "nodes/api" get "api/group_show" => "public#group_show", cell: "nodes/api" get "api/package_search" => "public#package_search", cell: "nodes/api" get "api/resource_search" => "public#resource_search", cell: "nodes/api" get "api/1/package_list" => "public#package_list", cell: "nodes/api" get "api/1/group_list" => "public#group_list", cell: "nodes/api" get "api/1/tag_list" => "public#tag_list", cell: "nodes/api" get "api/1/package_show" => "public#package_show", cell: "nodes/api" get "api/1/tag_show" => "public#tag_show", cell: "nodes/api" get "api/1/group_show" => "public#group_show", cell: "nodes/api" get "api/1/package_search" => "public#package_search", cell: "nodes/api" get "api/1/resource_search" => "public#resource_search", cell: "nodes/api" get "member/" => "public#index", cell: "nodes/member" get "member/:member" => "public#show", cell: "nodes/member" get "member/:member/datasets/(:filename.:format)" => "public#datasets", cell: "nodes/member" get "member/:member/apps/(:filename.:format)" => "public#apps", cell: "nodes/member" get "member/:member/ideas/(:filename.:format)" => "public#ideas", cell: "nodes/member" end end
require 'deliveryboy/loggable' require 'deliveryboy/plugins' require 'fileutils' module Deliveryboy class Maildir include Loggable attr_accessor :terminated def initialize(config) @throttle = (config[:throttle] || 5).to_i @filematch = config[:filematch] || "*.*" @dirmatch = config[:dirmatch] || "{new,cur,.}" @maildir = config[:maildir] # make a Maildir structure ["new", "cur", "tmp", "err"].each {|subdir| FileUtils.mkdir_p(File.join(@maildir, subdir))} @terminated = false @plugins = config[:plugins].collect {|hash| Deliveryboy::Plugins.load(hash[:script]).new(hash) } logger.info "#{@maildir} configured plugins: #{@plugins.collect {|p| p.class.name}.join(', ')}" end def handle(filename) logger.info "handling #{filename}" mailtxt = IO.read(filename) mailobj = Mail.new(mailtxt) mailobj.destinations.each_with_index do |recipient, index| logger.debug "recipient: #{recipient.inspect} ..." mail = (index == 0 ? mailobj : Mail.new(mailtxt)) mail.to_s unless mail.has_message_id? # generate unique message_id if absent mail.message_id = "#{mail.message_id}-#{index}" unless index == 0 @plugins.each do |plugin| break if plugin.handle(mail, recipient) == false # callback chain is broken when one plugin returns false end end File.delete filename if File.exists?(filename) rescue Exception # server must continue running so, # run "archive_mail" as first plugin logger.error $! if File.exists?(filename) err_filename = File.join(@maildir, "err", File.split(filename).last) logger.error "Failed mail archived as #{err_filename} ..." File.rename filename, err_filename end sleep @throttle end def get_filename @sorted_filenames && @sorted_filenames.shift || begin # batch operation for filename retrieval & mtime comparison @fullmatch ||= File.join(@maildir, @dirmatch, @filematch) # looks inside maildir/new/, maildir/cur/ and maildir/ itself. (avoids maildir/tmp/) @sorted_filenames = Dir[@fullmatch].sort_by {|f| test(?M, f)} # sort by mtime @sorted_filenames.shift end end def run while not @terminated sleep @throttle until filename = self.get_filename || @terminated self.handle(filename) unless @terminated end ensure logger.debug "#{@maildir} closed" end end end
module UserHelper def display_links(user) link = '' if current_user == user link = content_tag :span, 'Current user', class: 'bg-yellow' elsif current_user.pending?(user) link = content_tag :span, 'Pending...', class: 'bg-orange' elsif current_user.requested?(user) # rubocop:disable Layout/LineLength link << link_to('Accept', confirm_friendship_path(id: user.id), method: :put, class: 'btn-green') link << link_to('Decline', friendship_path(id: user.id), method: :delete, data: { confirm: 'Are you sure you want to decline friend request?' }, class: 'btn-red') elsif current_user.friend?(user) link << link_to('Remove Friendship', friendship_path(id: user.id), method: :delete, data: { confirm: 'Are you sure you want to remove friend?' }, class: 'btn-red') # rubocop:enable Layout/LineLength elsif !current_user.friend?(user) link << link_to('Invite to friendship', friendships_path(user_id: user.id), method: :post, action: :confirm, class: 'btn-green') end link.html_safe end end
require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:one) @test_user = { name: "test_user", email: "test_user@test.com", phone: "0700000001", password: "pass123", password_confirmation: 'pass123'} end test "should get the user signup form" do get "/signup" assert_response :success end test "should create user" do assert_difference('User.count') do post "/users", params: { user: @test_user} end end test "should show user profile" do get "/users/#{@user.id}" assert_response :success end test "should be able to edit user profile" do edited_user = @test_user edited_user[:name] = "new name" patch user_path(@user), params: {user: edited_user} assert_response :success end end
class CategoriesController < ApplicationController before_action :require_admin, except: [:index, :show] def index @categories = Category.paginate(page: params[:page], per_page: 5) #standard to use paginataion + in index page end def new @category = Category.new end def create #get the submission of new category @category = Category.new(category_params) if @category.save flash[:success] = "Category was successfully created" redirect_to categories_path else render 'new' end end def show #for showing single category article we have to define following to use in show page of categories @category = Category.find(params[:id]) @category_articles = @category.articles.paginate(page: params[:page], per_page: 5) end def edit @category = Category.find(params[:id]) end def update #update category name, handle the submission @category = Category.find(params[:id]) if @category.update(category_params) flash[:success] = "Category name was successfully updated" redirect_to category_path(@category) else render 'edit' end end private def category_params params.require(:category).permit(:name) end def require_admin if !logged_in? || (logged_in? and !current_user.admin?) flash[:danger] = "only admin can perform that action" redirect_to categories_path end end end
class CatMission < Delegator def initialize(cat:, mission:) @cat = cat @mission = mission end def __getobj__ @mission end def __setobj__(obj) @mission = obj end end
require 'spec_helper' describe SPV::Fixtures do let(:fixture1) { instance_double('SPV::Fixture', name: 'fixture1') } let(:fixture2) { instance_double('SPV::Fixture', name: 'fixture2') } let(:fixture3) { instance_double('SPV::Fixture', name: 'fixture3') } let(:fixture4) { instance_double('SPV::Fixture', name: 'fixture4') } let(:fixture5) { instance_double('SPV::Fixture', name: 'fixture5') } subject(:fixtures) { described_class.new([fixture1, fixture2, fixture3]) } describe '#exchange' do def exchange fixtures.exchange([fixture1, fixture3], [fixture4, fixture5]) end it 'removes "fixture1" and "fixture3" elements' do new_fixtures = exchange expect(new_fixtures).to_not include(fixture1, fixture3) end it 'adds "fixture4, fixture5" elements' do new_fixtures = exchange expect(new_fixtures).to include(fixture4, fixture5) end it 'does not touch the original object' do exchange expect(fixtures).to include(fixture1, fixture2, fixture3) end end describe '#replace' do context 'when fixtures are passed' do it 'does not change the original object' do fixtures.replace([fixture4, fixture5]) expect(fixtures).to include(fixture1, fixture2, fixture3) expect(fixtures).to_not include(fixture4, fixture5) end it 'returns a new container with fixtures' do new_fixtures = fixtures.replace([fixture4, fixture5]) expect(new_fixtures).to include(fixture4, fixture5) expect(new_fixtures).to_not include(fixture1, fixture2, fixture3) end end context 'when no fixtures are passed' do it 'returns itself' do new_fixtures = fixtures.replace([]) expect(new_fixtures).to eq(fixtures) end end end describe '#union' do it 'does not change the original object' do fixtures.union([fixture4, fixture5]) expect(fixtures).to include(fixture1, fixture2, fixture3) expect(fixtures).to_not include(fixture4, fixture5) end it 'returns a new container with fixtures' do new_fixtures = fixtures.union([fixture4, fixture5]) expect(new_fixtures).to include(fixture1, fixture2, fixture3, fixture4, fixture5) end end end
class SubscriptionsController < ApplicationController before_action :authenticate_user! def new end def create if current_user.learner.stripe_customer_id.nil? save_the_customer else retrieve_customer end @coach = Coach.find(params[:subscriptions][:coach_id]) Stripe.api_key = "#{@coach.access_code}" # Create a Token from the existing customer on the platform's account token = Stripe::Token.create( {:customer => @customer.id }, {:stripe_account => @coach.uid } # id of the connected account ) # Create a Customer customer = Stripe::Customer.create( :source => token.id, :email => current_user.email ) customer.subscriptions.create( :plan => 'weekly_subscription', :application_fee_percent => 10 ) if !customer.default_source.nil? create_chat_channel end rescue Stripe::CardError => e flash[:error] = e.message redirect_to user_path(@coach.user.id) end def cancel find_customer @customer.subscriptions.first.delete current_user.save change_chat_to_inactive flash[:alert] = "Your subscription has been canceled. Hope you got the help you were needing!" redirect_to user_path(current_user) end def find_customer user = User.find(params[:user_id]) @coach = user.coach Stripe.api_key = @coach.access_code customers = Stripe::Customer.all customers.each_with_index do |customer,index| if customer.email == current_user.email return @customer = customers.data[index] end end end def save_the_customer Stripe.api_key = ENV["STRIPE_API_KEY"] # Get the credit card details submitted by the form token_id = params[:stripeToken] # Create a Customer @customer = Stripe::Customer.create( :source => token_id, :description => "#{current_user.first_name} #{current_user.last_name}'s account." ) current_user.learner.update_attribute(:stripe_customer_id, @customer.id) current_user.learner.save end def retrieve_customer Stripe.api_key = ENV["STRIPE_API_KEY"] @customer = Stripe::Customer.retrieve(current_user.learner.stripe_customer_id) end def create_chat_channel @chat = Chat.find_or_create_by(learner_id: current_user.learner.id, coach_id: @coach.id) @chat.update_attribute(:active, true) @chat.save flash[:notice] = "Thanks for your subscription! Your payment was successful." redirect_to chat_path(@chat) end def change_chat_to_inactive @chat = Chat.find_by learner_id: current_user.learner.id, coach_id: @coach.id @chat.update_attribute(:active, false) @chat.save end end
#encoding: utf-8 require 'spec_helper' describe 'server' do describe 'version' do it "should be string" do zbx.server.version.should be_kind_of(String) end it "should be 2.4.x" do zbx.server.version.should match(/2\.4\.\d+/) end end end
# == Schema Information # # Table name: shipment_fees # # id :integer not null, primary key # province_id :integer # city_id :integer # destination_name :string(255) # price :float(24) # created_at :datetime not null # updated_at :datetime not null # class ShipmentFee < ActiveRecord::Base belongs_to :province belongs_to :city before_save :set_destination_name def set_destination_name self.destination_name = self.province.name + (self.city ? "/#{self.city.name}" : '') end end
module OpenAPIParser::MediaTypeSelectable private # select media type by content_type (consider wild card definition) # @param [String] content_type # @param [Hash{String => OpenAPIParser::Schemas::MediaType}] content # @return [OpenAPIParser::Schemas::MediaType, nil] def select_media_type_from_content(content_type, content) return nil unless content_type return nil unless content if (media_type = content[content_type]) return media_type end # application/json => [application, json] splited = content_type.split('/') if (media_type = content["#{splited.first}/*"]) return media_type end if (media_type = content['*/*']) return media_type end nil end end
class FriendshipsController < ApplicationController before_action :set_friendship, only: [:show, :edit, :update, :destroy] # POST /friendships # POST /friendships.json def create @friendship = current_user.friendships.build(friend_id: params[:friend_id]) if @friendship.save redirect_to profile_path, notice: 'Added friend' else redirect_to profile_path, error: 'Unable to add friend' end end # DELETE /friendships/1 # DELETE /friendships/1.json def destroy @friendship = current_user.friendships.find(params[:id]) @friendship.destroy flash[:notice] = 'Friendship destroyed' redirect_to current_user end private def set_friendship @friendship = Friendship.find(params[:id]) end def friendship_params params.require(:friendship).permit(:user_id, :friend_id) end end
class AddUserStatsColumns < ActiveRecord::Migration def self.up add_column :user_stats, :num_full_reviews, :integer add_column :user_stats, :num_quick_reviews, :integer end def self.down remove_column :user_stats, :num_full_reviews remove_column :user_stats, :num_quick_reviews end end
require 'spec_helper' require_relative '../bin/http_response' RESPONSE1 = %{HTTP/1.1 200 OK Server: nginx/1.4.6 (Ubuntu) Date: Tue, 06 May 2014 02:17:16 GMT Content-Type: text/html Last-Modified: Sun, 27 Apr 2014 04:03:41 GMT Transfer-Encoding: chunked Connection: keep-alive Content-Encoding: gzip <!DOCTYPE html> <html lang="en"> <head><meta charset="utf-8" /> <meta name="description" content="should i test private methods?" /> <meta name="keywords" content="test,private,methods,oo,object,oriented,tdd" /> <title>Should I Test Private Methods?</title> </head> <body> <div style='font-size: 96px; font-weight: bold; text-align: center; padding-top: 200px; font-family: Verdana, Helvetica, sans-serif'>NO</div> <!-- Every time you consider testing a private method, your code is telling you that you haven't allocated responsibilities well. Are you listening to it? --> </body> </html>} RESPONSE2 = %{HTTP/1.1 200 OK Server: nginx Date: Tue, 06 May 2014 02:15:51 GMT Content-Type: application/json; charset=utf-8 Transfer-Encoding: chunked Connection: keep-alive Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true Access-Control-Allow-Methods: GET, POST {"coord":{"lon":-0.13,"lat":51.51},"sys":{"message":0.0346,"country":"GB","sunrise":1399350122,"sunset":1399404728},"base":"cmc stations"}} describe HttpResponse do it "returns a hash of headers" do response = HttpResponse.new(RESPONSE1) actual = response.headers expected = { :server => "nginx/1.4.6 (Ubuntu)", :date => "Tue, 06 May 2014 02:17:16 GMT", :content_type => "text/html", :last_modified => "Sun, 27 Apr 2014 04:03:41 GMT", :transfer_encoding => "chunked", :connection => "keep-alive", :content_encoding => "gzip" } expect(actual).to eq expected end it "returns the body of the response" do response = HttpResponse.new(RESPONSE1) actual = response.body expected = %{<!DOCTYPE html> <html lang="en"> <head><meta charset="utf-8" /> <meta name="description" content="should i test private methods?" /> <meta name="keywords" content="test,private,methods,oo,object,oriented,tdd" /> <title>Should I Test Private Methods?</title> </head> <body> <div style='font-size: 96px; font-weight: bold; text-align: center; padding-top: 200px; font-family: Verdana, Helvetica, sans-serif'>NO</div> <!-- Every time you consider testing a private method, your code is telling you that you haven't allocated responsibilities well. Are you listening to it? --> </body> </html>} expect(actual).to eq expected end it "returns the response code" do response = HttpResponse.new(RESPONSE1) actual = response.status_code expected = 200 expect(actual).to eq expected end it "returns nil if content type is not json, else nil" do response = HttpResponse.new(RESPONSE1) actual = response.response_json expected = nil expect(actual).to eq expected end it "returns ruby hash of body if content type is json" do response = HttpResponse.new(RESPONSE2) actual = response.response_json expected = { "coord" => { "lon" => -0.13, "lat" => 51.51 }, "sys" => { "message" => 0.0346, "country" => "GB", "sunrise" => 1399350122, "sunset" => 1399404728 }, "base" => "cmc stations" } expect(actual).to eq expected end it "saves body in temp folder if content type is text" do if File.exist?("./tmp/test.html") File.delete("./tmp/test.html") end response = HttpResponse.new(RESPONSE1) response.response_html actual = File.read(File.new("./tmp/test.html")) expected = %{<!DOCTYPE html> <html lang="en"> <head><meta charset="utf-8" /> <meta name="description" content="should i test private methods?" /> <meta name="keywords" content="test,private,methods,oo,object,oriented,tdd" /> <title>Should I Test Private Methods?</title> </head> <body> <div style='font-size: 96px; font-weight: bold; text-align: center; padding-top: 200px; font-family: Verdana, Helvetica, sans-serif'>NO</div> <!-- Every time you consider testing a private method, your code is telling you that you haven't allocated responsibilities well. Are you listening to it? --> </body> </html>\n} expect(actual).to eq expected end end
require 'rails_helper' RSpec.describe Space, type: :model do it 'returns a status' do coordinates = double("Coordinates", :coordinate => "A1") board = double("Board", :length => 4) space = Space.new(coordinates, board) expect(space.status).to eq("Not Attacked") end it 'attack' do coordinates = double("Coordinates", :coordinate => "A1") board = double("Board", :length => 4) space = Space.new(coordinates, board) space.attack! expect(space.status).to eq("Miss") end it 'can make a space occupied' do coordinates = "A1" board = Board.new(4) sm_ship = Ship.new(2) space = Space.new(coordinates, board) space.occupy!(sm_ship) result = space.occupied? expect(result).to eq(true) end it 'can tell if space is occupied' do coordinates = "A1" board = Board.new(4) sm_ship = Ship.new(2) space = Space.new(coordinates, board) placed_ship = ShipPlacer.new( board: board, ship: sm_ship, start_space: "A1", end_space: "A2").run result = board.board.first.first["A1"].occupied? expect(result).to eq(true) end end
#encoding: utf-8 class Moip::Invoice < Moip::Model include HTTParty include Moip::Header attr_accessor :id, :amount, :subscription_code, :occurrence, :status, :items, :plan, :customer, :creation_date def attributes { "id" => id, "amount" => amount, "subscription_code" => subscription_code, "occurrence" => occurrence, "status" => status, "items" => items, "plan" => plan, "customer" => customer, "creation_date" => creation_date } end def invoices= hash @invoices = [] hash.each do |e| invoice = Moip::Invoice.new invoice.set_parameters e @invoices << invoice end @invoices end def full_status status = case self.status['code'] when 1 then "Em aberto" # A fatura foi gerada mas ainda não foi paga pelo assinante. when 2 then "Aguardando Confirmação" # A fatura foi paga pelo assinante, mas o pagamento está em processo de análise de risco. when 3 then "Pago" # A fatura foi paga pelo assinante e confirmada. when 4 then "Não Pago" # O assinante tentou pagar a fatura, mas o pagamento foi negado pelo banco emissor do cartão de crédito ou a análise de risco detectou algum problema. Veja os motivos possíveis. when 5 then "Atrasada" # O pagamento da fatura foi cancelado e serão feitas novas tentativas de cobrança de acordo com a configuração de retentativa automática. end status end def invoices @invoices ||= self.invoices=(self.load) end def load list = self.class.get(base_url(:subscriptions, :code => self.subscription_code, :status => "invoices"), default_header).parsed_response self.invoices = list["invoices"] end def find response = self.class.get(base_url(:invoices, :code => self.id), default_header).parsed_response self.set_parameters response unless response.nil? end def payments @payments ||= Moip::Payment.build(:invoice => self.id).payments end def retry response = self.class.post(base_url(:invoices, :code => self.id, :status => "retry"), default_header).parsed_response end def self.retry id response = self.class.post(base_url(:payments, :code => id, :status => "retry"), default_header).parsed_response end end
module GoFish class Game attr_accessor :num_players, :deck, :players def initialize(num_players) @num_players = num_players @players = [] @deck = Deck.new.shuffle! @starting_player = pick_starting_player(num_players) end def create_player(name) player = GoFish::Player.new(name) player.draw_five_cards(@deck) @players.push(player) return player end def pick_starting_player(num_players) starter_index = rand(num_players) return @players[starter_index] end def game_over? @players.each do |player| if !player.secret_hand_empty? return false end end return true end def turn(player) end end end
Sequel.migration do up do create_table(:tags) do primary_key :id String :name end create_table(:activities_tags) do foreign_key :activity_id, :activities foreign_key :tag_id, :tags end end end