text
stringlengths
10
2.61M
feature "Entity Class - Create" do context 'Visitor' do scenario "Access invalid" do entity_class = (create :entity_class) visit edit_entity_class_path entity_class expect(current_path).to eq new_session_path end end context 'Admin' do let(:user) { create :user} background do login user.email, user.password end scenario "Success", js: true do entity_class = create :entity_class entity_class_new = build :entity_class entity_class_responsible = build :entity_class_responsible state = create(:state, acronym: "MG") city = create(:city, name: "Contagem", state: state) state_2 = create(:state, acronym: "BH") city_2 = create(:city, name: "Teste", state: state_2) visit edit_entity_class_path entity_class fill_in "entity_class[name]", with: entity_class_new.name fill_in "entity_class[description]", with: entity_class_new.description fill_in "entity_class[zipcode]", with: "32341170" fill_in "entity_class[number]", with: entity_class_new.number sleep 5 fill_in "entity_class[complement]", with: entity_class_new.complement sleep 1 select_from_chosen state_2.acronym, :from => "entity_class[state_id]" select_from_chosen city_2.name, :from => "entity_class[city_id]" fill_in "entity_class[entity_class_responsibles_attributes][0][name]", with: entity_class_responsible.name fill_in "entity_class[entity_class_responsibles_attributes][0][office]", with: entity_class_responsible.office fill_in "entity_class[entity_class_responsibles_attributes][0][department]", with: entity_class_responsible.department fill_in "entity_class[entity_class_responsibles_attributes][0][whatsapp]", with: "(24) 21421-4141" fill_in "entity_class[entity_class_responsibles_attributes][0][skype]", with: entity_class_responsible.skype fill_in "entity_class[entity_class_responsibles_attributes][0][email_users_attributes][0][email]", with: "email@email.com" click_button "Salvar" sleep 1 expect(page).to have_content "Entidade de classe editada com sucesso" expect(current_path).to eq edit_entity_class_path entity_class expect(EntityClass.first.name).to eq entity_class_new.name expect(EntityClass.first.description).to eq entity_class_new.description expect(EntityClass.first.address).to eq "Rua Moassy" expect(EntityClass.first.number).to eq entity_class_new.number expect(EntityClass.first.complement).to eq entity_class_new.complement expect(EntityClass.first.district).to eq "Novo Eldorado" expect(EntityClass.first.city_id).to eq city_2.id expect(EntityClass.first.state_id).to eq state_2.id expect(EntityClass.first.entity_class_responsibles[0].name).to eq entity_class_responsible.name expect(EntityClass.first.entity_class_responsibles[0].office).to eq entity_class_responsible.office expect(EntityClass.first.entity_class_responsibles[0].department).to eq entity_class_responsible.department expect(EntityClass.first.entity_class_responsibles[0].whatsapp).to eq "(24) 21421-4141" expect(EntityClass.first.entity_class_responsibles[0].skype).to eq entity_class_responsible.skype expect(EntityClass.first.entity_class_responsibles[0].email_users[0].email).to eq "email@email.com" end scenario "Success adding responsible", js: true do entity_class = create :entity_class entity_class_responsible = build :entity_class_responsible entity_class_responsible_2 = build :entity_class_responsible state = create(:state, acronym: "MG") city = create(:city, name: "Contagem", state: state) visit edit_entity_class_path entity_class click_button "Adicionar responsável" fill_in "entity_class[name]", with: entity_class.name fill_in "entity_class[description]", with: entity_class.description fill_in "entity_class[zipcode]", with: "32341170" fill_in "entity_class[number]", with: entity_class.number sleep 5 fill_in "entity_class[complement]", with: entity_class.complement select_from_chosen state.acronym, :from => "entity_class[state_id]" select_from_chosen city.name, :from => "entity_class[city_id]" fill_in "entity_class[entity_class_responsibles_attributes][0][name]", with: entity_class_responsible.name fill_in "entity_class[entity_class_responsibles_attributes][0][office]", with: entity_class_responsible.office fill_in "entity_class[entity_class_responsibles_attributes][0][department]", with: entity_class_responsible.department fill_in "entity_class[entity_class_responsibles_attributes][0][whatsapp]", with: "(24) 21421-4141" fill_in "entity_class[entity_class_responsibles_attributes][0][skype]", with: entity_class_responsible.skype fill_in "entity_class[entity_class_responsibles_attributes][0][email_users_attributes][0][email]", with: "email@email.com" fill_in "entity_class[entity_class_responsibles_attributes][1][name]", with: entity_class_responsible_2.name fill_in "entity_class[entity_class_responsibles_attributes][1][office]", with: entity_class_responsible_2.office fill_in "entity_class[entity_class_responsibles_attributes][1][department]", with: entity_class_responsible_2.department fill_in "entity_class[entity_class_responsibles_attributes][1][whatsapp]", with: "(24) 21421-4141" fill_in "entity_class[entity_class_responsibles_attributes][1][skype]", with: entity_class_responsible_2.skype fill_in "entity_class[entity_class_responsibles_attributes][1][email_users_attributes][0][email]", with: "email@email.com" sleep 1 click_button "Salvar" sleep 1 expect(page).to have_content "Entidade de classe editada com sucesso" expect(current_path).to eq edit_entity_class_path entity_class expect(EntityClass.first.name).to eq entity_class.name expect(EntityClass.first.description).to eq entity_class.description expect(EntityClass.first.address).to eq "Rua Moassy" expect(EntityClass.first.number).to eq entity_class.number expect(EntityClass.first.complement).to eq entity_class.complement expect(EntityClass.first.district).to eq "Novo Eldorado" expect(EntityClass.first.city_id).to eq city.id expect(EntityClass.first.state_id).to eq state.id expect(EntityClass.first.entity_class_responsibles[0].name).to eq entity_class_responsible.name expect(EntityClass.first.entity_class_responsibles[0].office).to eq entity_class_responsible.office expect(EntityClass.first.entity_class_responsibles[0].department).to eq entity_class_responsible.department expect(EntityClass.first.entity_class_responsibles[0].whatsapp).to eq "(24) 21421-4141" expect(EntityClass.first.entity_class_responsibles[0].skype).to eq entity_class_responsible.skype expect(EntityClass.first.entity_class_responsibles[1].name).to eq entity_class_responsible_2.name expect(EntityClass.first.entity_class_responsibles[1].office).to eq entity_class_responsible_2.office expect(EntityClass.first.entity_class_responsibles[1].department).to eq entity_class_responsible_2.department expect(EntityClass.first.entity_class_responsibles[1].whatsapp).to eq "(24) 21421-4141" expect(EntityClass.first.entity_class_responsibles[1].skype).to eq entity_class_responsible_2.skype expect(EntityClass.first.entity_class_responsibles[1].email_users[0].email).to eq "email@email.com" end end end
require 'rails_helper' RSpec.describe "events" do describe "POST #create" do it "create a new event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } service = create(:service, user_id: user.id) valid_attributes = attributes_for(:event).merge(service_id: service.id) post "/api/events", params: valid_attributes, headers: header expect(response).to be_success expect(response).to have_http_status(201) json = JSON.parse(response.body) expect(json["id"]).not_to be_nil expect(json["desc"]).to eq valid_attributes[:desc] expect(format_json_time(json["start_at"])).to eq valid_attributes[:start_at] expect(format_json_time(json["stop_at"])).to eq valid_attributes[:stop_at] expect(json["address"]).to eq valid_attributes[:address] end end describe "POST #vote" do it "vote a event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } service = create(:service, all_votes: 0, good_votes: 0) event = create(:event, service_id: service.id) post "/api/events/#{event.id}/vote", params: {scope: 3}, headers: header expect(response).to be_success expect(response).to have_http_status(201) expect(event.votes_for.size).to eq 1 service.reload expect(service.all_votes).to eq 1 expect(service.good_votes).to eq 1 end it "vote a event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } service = create(:service, all_votes: 0, good_votes: 0) event = create(:event, service_id: service.id) post "/api/events/#{event.id}/vote", params: {scope: 3}, headers: header post "/api/events/#{event.id}/vote", params: {scope: 3}, headers: header expect(response).to be_success expect(response).to have_http_status(201) expect(event.votes_for.size).to eq 1 service.reload expect(service.all_votes).to eq 1 expect(service.good_votes).to eq 1 end end describe "PATCH #update" do it "update the event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id) new_attributes = { start_at: Time.now, stop_at: Time.now + 10.minutes, desc: "new desc", address: "new address" } patch "/api/events/#{event.id}", params: new_attributes , headers: header expect(response).to be_success expect(response).to have_http_status(200) event.reload expect(event.start_at.to_i).to eq new_attributes[:start_at].to_i expect(event.stop_at.to_i).to eq new_attributes[:stop_at].to_i expect(event.desc).to eq new_attributes[:desc] expect(event.address).to eq new_attributes[:address] end end describe "DELETE #destroy" do it "delete the requested event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id) delete "/api/events/#{event.id}", headers: header expect(response).to be_success expect(response).to have_http_status(200) expect(Event.count).to eq 1 end it "failed to return money when delete the requested event" do user = create(:user, balance: 0) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id) order = create(:order, event_id: event.id, state: "已预订") delete "/api/events/#{event.id}", headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["message"]).to eq "账户的金额不够" end it "return money when delete the requested event" do user = create(:user, balance: 100) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id) order = create(:order, event_id: event.id, state: "已预订", amount: 10) delete "/api/events/#{event.id}", headers: header expect(response).to be_success expect(response).to have_http_status(200) expect(user.reload.balance).to eq 90.0 expect(Message.count).to eq 2 # order cancel, event delete end end describe "GET #show" do it "get the requested event" do user = create(:user) service = create(:service, user_id: user.id) event = create(:event, service_id: service.id) get "/api/events/#{event.id}" expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["service"]["id"]).to eq service.id expect(json["service"]["poster"]).to eq service.poster expect(json["service"]["title"]).to eq service.title expect(json["desc"]).to eq event.desc expect(json["id"]).to eq event.id expect(json["organizer"]["id"]).to eq user.id expect(json["organizer"]["avatar"]).to eq user.avatar expect(json["organizer"]["name"]).to eq user.name expect(json["organizer"]["mobile"]).to eq user.mobile expect(json["start_at"].to_datetime.to_i).to eq event.start_at.to_i expect(json["stop_at"].to_datetime.to_i).to eq event.stop_at.to_i expect(json["address"]).to eq event.address expect(json["quota"]).to eq event.quota expect(json["proportion"]).to eq "#{event.orders.count}/#{event.quota}" expect(json["price"].to_f).to eq event.price expect(json["state"]).to eq "进行中" expect(json["status"]).to be_nil end it "ordered the event: 已预订" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event) order = create(:order, user_id: user.id, event_id: event.id, state: "已预订") get "/api/events/#{event.id}", headers: header expect(JSON.parse(response.body)["status"]).to eq "已预订" expect(JSON.parse(response.body)["order_id"]).to eq order.id end it "ordered the event: 待付款" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event) order = create(:order, user_id: user.id, event_id: event.id, state: "待付款") get "/api/events/#{event.id}", headers: header expect(JSON.parse(response.body)["status"]).to eq "待付款" expect(JSON.parse(response.body)["order_id"]).to eq order.id end it "has the event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } service = create(:service, user_id: user.id) event = create(:event, service_id: service.id) get "/api/events/#{event.id}", headers: header expect(JSON.parse(response.body)["status"]).to eq "分享" end end describe "GET #index" do it "get event list in a certain day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, start_at: Time.now, user_id: user.id) get "/api/events", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["events"].first["id"]).to eq event.id expect(json["events"].first["start_at"]).not_to be_nil expect(json["events"].first["stop_at"]).not_to be_nil expect(json["events"].first["desc"]).to eq event.desc expect(json["events"].first["address"]).to eq event.address expect(json["events"].first["organizer"]["id"]).to eq user.id expect(json["events"].first["organizer"]["avatar"]).to eq user.avatar expect(json["events"].first["organizer"]["name"]).to eq user.name expect(json["events"].first["type"]).to eq "organizer" expect(json["events"].first["service"]["id"]).to eq event.service_id expect(json["events"].first["service"]["title"]).to eq event.service.title expect(json["events"].first["price"]).to eq event.price.to_s expect(json["events"].first["state"]).to eq "进行中" end it "get event list in a wrong day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, start_at: Time.now, user_id: user.id) get "/api/events", params: {day: Date.today + 1.day}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["events"].count).to eq 0 end it "get ordered event list in a certain day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, start_at: Time.now) order = create(:order, event_id: event.id, user_id: user.id) get "/api/events", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["events"].count).to eq 1 expect(json["events"].first["type"]).to eq "participant" expect(json["events"].first["proportion"]).to eq "1/#{event.quota}" end it "get ordered event list in a wrong day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, start_at: Time.now) order = create(:order, event_id: event.id, user_id: user.id) get "/api/events", params: {day: Date.today + 1.day}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["events"].count).to eq 0 end it "get two ordered event list in a certain day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, start_at: Time.now) another_event = create(:event, start_at: Time.now) create(:order, event_id: event.id, user_id: user.id) create(:order, event_id: another_event.id, user_id: user.id) get "/api/events", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["events"].count).to eq 2 end it "not include other user's event" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, start_at: Time.now) another_event = create(:event, start_at: Time.now) create(:order, event_id: event.id, user_id: user.id) get "/api/events", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["events"].count).to eq 1 end end describe "GET #count_by_week" do it "get event count in a week according the given day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id, start_at: Time.now) get "/api/events/count_by_week", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) week_count = [0,0,0,0,0,0,0] week_count[Date.today.wday - 1] = 1 expect(json).to eq week_count end it "get event count in week: 1 event in monday" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id, start_at: Time.now.beginning_of_week + 8.hours) get "/api/events/count_by_week", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) week_count = [1,0,0,0,0,0,0] expect(json).to eq week_count end it "get event count in week: 1 event in sunday" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id, start_at: Time.now.end_of_week) get "/api/events/count_by_week", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) week_count = [0,0,0,0,0,0,1] expect(json).to eq week_count end end describe "GET #count_by_month" do it "get event count in a month according the given day" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id, start_at: Time.now) get "/api/events/count_by_month", params: {day: Date.today}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) month_count = Array.new(Date.today.end_of_month.day,0) month_count[Date.today.day - 1] = 1 expect(json).to eq month_count end it "get event count in a month according the given day: last month" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id, start_at: Time.now - 1.month) get "/api/events/count_by_month", params: {day: (Date.today - 1.month).strftime("%Y-%-m-%-d")}, headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) month_count = Array.new((Date.today - 1.month).end_of_month.day,0) month_count[(Date.today - 1.month).day - 1] = 1 expect(json).to eq month_count end end describe "GET #last_five_addresses" do it "get last_five_addresses" do user = create(:user) header = { authorization: ActionController::HttpAuthentication::Token.encode_credentials("#{user.authentication_token}") } event = create(:event, user_id: user.id) get "/api/events/last_five_addresses", headers: header expect(response).to be_success expect(response).to have_http_status(200) json = JSON.parse(response.body) expect(json["last_five_addresses"]).to eq [event.address] end end end
class Person include Mongoid::Document include Mongoid::Slug field :name slug :name, :as => :permalink, :permanent => true, :scope => :author embeds_many :relationships referenced_in :author, :inverse_of => :characters end
array = ["one", "two", "three"] array.each_with_index do |word, number| puts "#{number + 1}) #{word}" end
# write a method that returns true if the string # passed is as an arguement is a palindrome # false if otherwise # a palindrome reads the same forwards and backwards # for this exercise, case, punctuation and spaces matter # Examples: def palindrome?(string) string == string.reverse! end p palindrome?('madam') == true p palindrome?('Madam') == false # (case matters) p palindrome?("madam i'm adam") == false # (all characters matter) p palindrome?('356653') == true
module Datamappify module Repository module QueryMethod class Find < Method # @param options (see Method#initialize) # # @param id [Integer] def initialize(options, id) super @id = id end # @return [Entity, nil] def perform entity = data_mapper.entity_class.new entity.id = @id if dispatch_criteria_to_default_source(:Exists, entity) dispatch_criteria_to_providers(:FindByKey, entity) else entity = nil end entity end # @see Method#reader? def reader? true end end end end end
class Town < ActiveRecord::Base belongs_to :municipality validates :kind, presence: true validates :code, presence: true, uniqueness: true validates :name, presence: true validates :municipality_id, presence: true delegate :state, to: :municipality def full_name components = [name_with_kind] components << I18n.t('teritorrial_divisions.municipality', name: municipality.name) if municipality.name != name components << I18n.t('teritorrial_divisions.state', name: state.name) if state.name != name && state.name != municipality.name components.join(', ') end def name_with_kind "#{kind} #{name}" end end
module AccessSchema class SchemaBuilder < BasicBuilder def self.build(&block) builder = new(Schema.new) builder.instance_eval(&block) Proxy.new(builder.schema) end def self.build_file(filename) builder = new(Schema.new) builder.instance_eval(File.read(filename)) Proxy.new(builder.schema) end def roles(&block) builder = RolesBuilder.new(schema) builder.instance_eval(&block) end def asserts(&block) builder = AssertsBuilder.new(schema) builder.instance_eval(&block) end def resource(name, &block) resource = Resource.new(name.to_s) builder = ResourceBuilder.new(resource) builder.instance_eval(&block) schema.add_resource(resource) end end end
require 'securerandom' module TestSupport module Data def metadata_attributes metadata_response.merge(tasks_response) end def metadata_response { 'Cluster' => cluster, 'ContainerInstanceArn' => container_instance_arn, 'Version' => ecs_agent_version } end def tasks_response { 'Tasks' => [task_data] } end def task_data { 'Arn' => task_arn, 'DesiredStatus' => task_status, 'KnownStatus' => task_status, 'Family' => task_family, 'Version' => task_version, 'Containers' => [container_data] } end alias task_attributes task_data def container_data { 'DockerId' => docker_id, 'DockerName' => docker_name, 'Name' => container_name } end alias container_attributes container_data def account_id rand(10**12) end def cluster 'westeros' end def container_instance_arn "arn:aws:ecs:#{region}:#{account_id}:" \ "container-instance/#{container_instance_uuid}" end def container_name 'jaime' end def docker_id SecureRandom.hex(32) end def docker_name "ecs-#{task_family}-#{task_version}-#{docker_name_id}" end def docker_name_id SecureRandom.hex(10) end def ecs_agent_version 'Amazon ECS Agent - v1.13.1 (efe53c6)' end def region 'us-east-1' end def task_arn "arn:aws:ecs:#{region}:#{account_id}:task/#{task_uuid}" end def task_family 'lannister' end def task_status 'RUNNING' end def task_uuid SecureRandom.uuid end alias container_instance_uuid task_uuid def task_version '4' end end end
class Post < ApplicationRecord acts_as_votable belongs_to :user has_many :comments, dependent: :destroy mount_uploader :image, ImageUploader has_many :taggings, dependent: :destroy has_many :tags, through: :taggings, dependent: :destroy # validations validates :image, presence: true validates :user_id, presence: true # creating all_tags for post def all_tags=(names) self.tags = names.split(",").map do |name| Tag.where(name: name.strip).first_or_create! end end def all_tags self.tags.map(&:name).join(", ") end def self.tagged_with(name) Tag.find_by_name!(name).posts end end
#!/usr/bin/env ruby # encoding: utf-8 # File: command_frame.rb # Created: 17/08/13 # # (c) Michel Demazure <michel@demazure.com> module JacintheManagement module GuiQt # Individual command frames for the manager GUI class CommandFrame < EmptyFrame slots :written, :execute, :help signals :output_written # @return[CommandFrame] frame for this command # @param[String] cmd call_name of command def self.with(cmd) new(Core::Command.fetch(cmd)) end # @param[String] the received text attr_reader :received # @param [Core::Command] command def initialize(command) super() @command = command @received = nil # noinspection RubyArgCount @str = GuiQt::Stream.new connect(@str, SIGNAL(:written), self, SLOT(:written)) set_color(BLUE) build_layout end # Build the layout def build_layout layout = Qt::VBoxLayout.new(self) # noinspection RubyArgCount label = Qt::Label.new("<b> #{@command.title}</b>") label.alignment = Qt::AlignHCenter label.tool_tip = @command.long_title.join("\n") layout.add_widget(label) layout.add_layout(buttons_layout) @answer = Qt::LineEdit.new layout.add_widget(@answer) end # Build the buttons layout # @return [Qt::HBoxLayout] buttons layout def buttons_layout buttons = Qt::HBoxLayout.new # noinspection RubyArgCount @button = Qt::PushButton.new('Exécuter') @button.setStyleSheet('* { background-color: rgb(255, 200, 200) }') buttons.add_widget(@button) connect(@button, SIGNAL(:clicked), self, SLOT(:execute)) # noinspection RubyArgCount help_button = Qt::PushButton.new('Description') buttons.add_widget(help_button) connect(help_button, SIGNAL(:clicked), self, SLOT(:help)) buttons end # Slot : execute the command and redirect the output to the inside stream def execute @answer.set_text('En cours') Qt::CoreApplication.process_events $stdout = @str puts "<b>------ Exécution de la commande '#{@command.title}'<\b>" puts '' @answer.text = @command.execute ? 'Succès' : 'ERREUR' puts '<b>------ Exécution terminée</b>' puts '' $stdout = STDOUT end # Slot : emit the signal 'output written' def written @received = @str.received emit(output_written) end # Slot : open the help MessageBox for this command def help text = "La commande \"#{@command.title}\"\n\n#{@command.help_text}" Qt::MessageBox.information(self, @command.title, text) end # enable/disable the execute button # @param [Boolean] bool whether the button has to be enabled def enabled=(bool) @button.enabled = bool end end end end
class AddPaidEventsCounterToStadium < ActiveRecord::Migration def up add_column :stadiums, :paid_events_counter, :integer, default: 0 Event.all.each(&:update_counter_cache) end def down remove_column :stadiums, :paid_events_counter, :integer, default: 0 end end
require 'json' class InventoryItem attr_reader :name attr_reader :sku attr_accessor :price attr_reader :bulk_deal_amount attr_reader :bulk_deal_price attr_reader :bonus_item_sku attr_reader :three_for_two def initialize(item_data) # These variables should always be present in the pricing rules @sku = item_data["sku"] @price = item_data["price"] # These are optional pricing rules @name = item_data["name"] @bulk_deal_amount ||= item_data["bulkDealAmount"] @bulk_deal_price ||= item_data["bulkDealPrice"] @bonus_item_sku ||= item_data["bonusItemSku"] @three_for_two ||= item_data["threeForTwo"] end end
#!/usr/bin/env ruby require_relative '../../../framework/Feature' class InformEuropeanEmergencyCall @@name = :inform_european_emergency_call @@feature = Feature.new(@@name) @@feature.add_alteration( :instance_attribute, :ERS, :emergency_call, 112) def self.get @@feature end def self.name @@name end end
# frozen_string_literal: true require 'rails_helper' describe HealthQuest::PatientGeneratedData::FHIRClient do include HealthQuest::PatientGeneratedData::FHIRClient describe '#accept_headers' do it 'has default Accept header' do expect(accept_headers).to eq({ 'Accept' => 'application/json+fhir' }) end end describe '#headers' do it 'raises NotImplementedError' do expect { headers }.to raise_error(NoMethodError, /NotImplementedError/) end end describe '#client' do let(:headers) { { 'X-VAMF-JWT' => 'abc123' } } it 'has a fhir_client' do expect(client).to be_an_instance_of(FHIR::Client) end end describe '#url' do it 'has a pgd path' do expect(url).to match('/smart-pgd-fhir/v1') end end end
require "open-uri" require "nokogiri" require "coveralls" Coveralls.wear! SimpleCov.command_name "pry-test" require_relative "../lib/pipe_envy" using PipeEnvy class PipeEnvyTest < PryTest::Test test "simple readme example" do assert "Ruby Rocks" | :upcase | :split == ["RUBY", "ROCKS"] end test "chained pipes" do output = "example" \ | :chars \ | :last \ | :upcase assert output == "E" end test "pipes with block" do output = [1, 2, 3, 4, 5, 6, 7, 8, 9] \ | [:select!, -> (i) { i.even? }] assert output == [2, 4, 6, 8] end test "complex pipeline" do output = (1..100) \ | :to_a \ | [:select!, -> (i) { i.even? }] \ | [:map, -> (i) { i ** 10 }] \ | :sum \ | Math.method(:sqrt) \ | :to_s \ | :chars \ | :reverse \ | [:[], 3] \ | :to_i assert output == 7 end # TODO: record http result so we don't request on each run test "chainable methods repo example" do output = "foo bar http://github.com/hopsoft/pipe_envy foo bar" \ | URI.method(:extract) \ | :first \ | URI.method(:parse) \ | :open \ | :readlines \ | :join \ | Nokogiri::HTML.method(:parse) \ | [:css, "h1"] \ | :first \ | :text \ | :strip assert output == "hopsoft/pipe_envy" end end
class Api::ServerMembersController < ApplicationController def create @server = Server.find_by(instant_invite: params[:instant_invite]) if @server current_user.servers << @server render 'api/servers/show', server: @server else render json: ['Server does not exist'], status: 404 end end def destroy end end
module CDI module V1 class StudentLearningTrackSerializer < SimpleLearningTrackSerializer has_many :categories, serializer: SimpleCategorySerializer, embed: :ids, embed_in_root_key: :linked_data, embed_in_root: true has_many :skills, serializer: SimpleSkillSerializer, embed: :ids, embed_in_root_key: :linked_data, embed_in_root: true end end end
require 'spec_helper' describe TvveetsController do describe "POST #create" do let(:user) { FactoryGirl.create(:user) } before { valid_sign_in user } context "with valid content" do let(:valid_tvveet) { FactoryGirl.build(:tvveet, user: user) } it "saves the new tvveet" do expect { post :create, tvveet: valid_tvveet.attributes }.to change(Tvveet, :count).by(1) end end context "with empty content" do let(:empty_tvveet) { FactoryGirl.build(:empty_content, user: user) } it "should not save the tvveet" do expect { post :create, tvveet: empty_tvveet.attributes }.not_to change(Tvveet, :count) end end end end
class Happening < ActiveRecord::Base belongs_to :creator, foreign_key: :creator_id, class_name: "User" has_many :rsvps has_many :attendees, through: :rsvps end
#encoding:utf-8 require 'nokogiri' require 'open-uri' require File.expand_path("../grabepg/grab_base.rb", __FILE__) require File.expand_path("../grabepg/grab_tvsou.rb", __FILE__) module Grabepg class GrabTvmao # To change this template use File | Settings | File Templates. #图片的获取: Net::HTTP.get(url) #图片的文件类型获取: attr_reader :channel #频道列表 attr_reader :site #网站地址 attr_reader :proxyindex #代理的索引 attr_reader :show_schedule #根据节目的时间表 attr_reader :img_down_path #图片下载路径存放 DEFAULT_GrabtvType=["cctv","satellite","digital",] DEFAULT_SITE = "http://www.tvmao.com" def initialize @grabbase = GrabBase.new end #批量从tvmao获取节目类型 #channel 节目表属于的屏道 #url 节目表获取的网络地址 #date 日期 #schedule 需要批量修改的时间表 #proxylist 代理列表 def get_show_type_by_batch(channel,url,date,schedule,proxylist) _schedule = {} schedule.each do |s| time = s["schedule_start"].gsub(":","").to_i _schedule.merge!(time=>s) end url = get_show_type_url(url,date) schedules = get_schedulelist_atday(channel,url,proxylist) type = nil schedules.each do |schedule| schedule_time_num = schedule["schedule_start"].gsub(":","").to_i if _schedule.has_key?(schedule_time_num) _schedule[schedule_time_num]["type"]=_schedule[schedule_time_num]["type"]|schedule["type"] p "*****************************************************************************************" p "Schedule: #{_schedule[schedule_time_num]}" p "schedule_logo_1: #{_schedule[schedule_time_num]["schedule_logo"]}" p "schedule_logo_2: #{_schedule[schedule_time_num][:schedule_logo]}" if _schedule[schedule_time_num]["schedule_logo"]=="" unless schedule["img"]=="" _schedule[schedule_time_num]["schedule_logo"]=schedule["img"] end end end end ret = [] _schedule.each do |key,value| ret << value end ret end #批量从tvmao获取节目类型 #channel 节目表属于的屏道 #url 节目表获取的网络地址 #date 日期 #time 节目开始时间 #proxylist 代理列表 def get_show_type(channel,url,date,time,proxylist) url = get_show_type_url(url,date) schedules = get_schedulelist_atday(channel,url,proxylist) _time_num = time.gsub(":","").to_i type = nil schedules.each do |schedule| schedule_time_num = schedule["schedule_start"].gsub(":","").to_i if _time_num==schedule_time_num type = schedule["type"] end end if type return type else return [] end end def get_show_type_url(url,date) whatday = 0 _date = date.split("(")[0] case _date when "星期一" whatday=1 when "星期二" whatday=2 when "星期三" whatday=3 when "星期四" whatday=4 when "星期五" whatday=5 when "星期六" whatday=6 when "星期日" whatday=7 end get_week_url = lambda {|url,whatday| _url = "http://www.tvmao.com" urls = [] _urls = url.split("-") 0.upto(1).each do |i| _url = _url+"#{_urls[i]}"+"-" end url = _url+"w#{whatday}.html" return url } return get_week_url.call(url,whatday) end #将星期的wday获取值转化为中文名 #conversion wady to chinese def conversion_what_day(whatday) ret = "星期" case whatday.to_i when 1 ret += "一" when 2 ret += "二" when 3 ret += "三" when 4 ret += "四" when 5 ret += "五" when 6 ret += "六" when 7 ret += "七" end ret end #如果时间为1~9的一位则为其在数字前加0补齐二位 def dispose_time(num) num = num.to_s if num.length < 2 num = "0"+num end num end #转化当前时间的格式 def get_week_date_time(time) month = time.month day = time.day whatday = time.wday ret = conversion_what_day(whatday) + "(" + dispose_time(month) + "-"+dispose_time(day)+")" ret end #前几天需要减去的num def del_day_num(day_num) ret = day_num*60*60*24 ret end #获取距离当前多少天的之前的日期 def get_time_day_prior(num) time = Time.now - del_day_num(num) ret = get_week_date_time(time) ret end #前面一周要删除的日期的列表 def del_time_list ret = [] time = Time.now wday = time.wday if(wday==1) for i in 0..7 ret<<get_time_day_prior(i) end end ret end #调用此方法的例子 def start #作用是获取俩个字符串的相似度 #get str1 and str2 similarity get_similarity_string = lambda { |str1,str2| _length = 0 type = 0 if str1.length>str2.length _length=str2.length type = 2 else _length=str1.length type =1 end _str_list = [] _str = "" for i in 0.._length case type when 2 n=i 0.upto(str1.length-1).each do |j| p "N: #{n}" if(str2[n]==str1[j]) _str =_str+str2[n] n = n+1 p "Str = #{_str}" else _str_list << _str _str = "" end end when 1 n=i 0.upto(str2.length-1).each do |j| p "N: #{n}" if(str1[n]==str2[j]) _str =_str+str1[n] n=n+1 p "Str = #{_str}" else _str_list << _str _str = "" end end end end p _str_list _str = "" _str_list.each do |str| if _str.length<str.length _str=str end end _str } path = "/home/zql/workspace/New/smart_remote/img_path" channel_list = GrabTvmao.getchannels(path) channel_urls = channel_list['channel_urls'] channel_infos = channel_list['channel_info'] p "Channel img save file,path='#{GrabTvmao.img_down_path}'" proxy_list=GrabTvmao.get_topfast_list(5) #get_topfast_list 参数是代表最慢用时 单位秒 #Use for Test p "************************************" p "proxy_list:#{proxy_list}" p "************************************" bool_start = false channel_urls.each do |channel,url| if(channel=="CCTV16") bool_start = true end if bool_start previous_show_name = "" channel_info = channel_infos[channel] channel_name = channel_info["channel_name"] channel_type = channel_info["channel_type"] channel_id = channel_info["channel_id"] channel_img_path = channel_info["img_path"] #channel,herf,proxylist,day_num=7 start_time=0 use_num =1 #getScheduleAssignDate参数: # channel 频道 # herf 频道地址 # proxylist 代理列表 # start_num 开始时间 int 为开始时间与今天的差值 正数代表今天之后的第几天 负数代表今天之前的第几天 # day_num 抓取的时间段天数 # img_dir_down_path 图片网络地址保存路径 有默认值 可不设置 schedule_list=GrabTvmao.getScheduleAssignDate(channel,url,proxy_list,start_time,use_num) #抓取的七天后的1天的数据 end end end def img_down_path @img_down_path end #获取网站的频道表 #img_path 图片存放路径 def getchannels(img_dir_path) @channel = [] @site=DEFAULT_SITE @proxyindex = 0 @img_down_dir_path = img_dir_path @img_down_file = File.new(File.join(img_dir_path,"channel_img_down_path"),'w+') channel_urls = {} channel_info = {} get_url =lambda { |type| @site + "/program/duration/#{type}/w1.html" unless (type.nil?||type.empty?) } get_channel_id = lambda {|url| channel_id = url.split("/")[2].split("-")[1] unless (url.nil?||url.empty?) } DEFAULT_GrabtvType.each do |type| url = get_url.call(type) p url doc = Nokogiri::HTML(open(url)) p doc.content p "*************************************************************" doc.css('td[class="tdchn"]').each do |td| channel_name=td.content herf = "" td.css('a').each do |a| herf=a['href'] end channel_id = get_channel_id.call(herf) #获取频道图片的地址 img_path = "http://static.haotv.me/channel/logo/#{channel_id}.jpg" @img_down_file.puts("#{channel_id}:#{img_path}") @channel<<({channel_id=>{name:channel_name,herf:herf,type:type}}) channel_info.merge!({channel_id=>{"channel_name"=>channel_name,"channel_type"=>type,"channel_id"=>channel_id,"img_path"=>img_path}}) channel_urls.merge!({channel_id=>herf}) end end @img_down_file.close p "Channel: #{@channel}" {"channel_info"=>channel_info,"channel_urls"=>channel_urls} end def err_doc_proxy(proxy,proxylist,url="",err="") if proxy.empty?||proxy.nil? proxylist.delete_at[@proxyindex] end unless @no_firest @no_firest = 0 end @no_firest += 1 p "*************************Proxy:#{proxy}, url:#{url} Error:#{err}" #proxylist.delete(proxy) #删除出错的代理 但如果是此网页错误则会引起BUG待修复 @proxyindex += 1 @proxyindex=@proxyindex%@size doc=get_doc_with_proxy(proxylist,url) if @no_firest<4 unless @no_firest<4 @no_firest=0 raise RuntimeError,"Error: #{err}" end doc end #使用代理获取url的html的doc值 def get_doc_with_proxy(proxylist,url) unless proxylist.nil?||proxylist.empty? unless @proxyindex @proxyindex = 0 end @size = proxylist.size @proxyindex=@proxyindex%proxylist.size if(proxylist[@proxyindex]) proxy = proxylist[@proxyindex] else proxy = proxylist[@proxyindex+1] end begin doc = Nokogiri::HTML(open(url,:proxy=>"#{proxy}").read) unless proxy.nil?||proxy.empty? if doc.nil? p "DOC is nil" doc=err_doc_proxy(proxy,proxylist,url,"doc nil") @no_firest=0 end @no_firest = 0 rescue => err p "IN Rescue" doc=err_doc_proxy(proxy,proxylist,url,err.to_s) @no_firest=0 p "Get DOC" @proxyindex += 1 @proxyindex=@proxyindex%@size return doc end @proxyindex += 1 @proxyindex=@proxyindex%@size else begin doc = Nokogiri::HTML(open(url).read) if proxy.nil?||proxy.empty? rescue => err p "Error : Proxy:#{proxy}, url:#{url}" raise RuntimeError,"Error: #{err.to_s} Method:get_doc_with_proxy" end end doc end #获取某天的节目表 def get_schedulelist_atday(channel,url,proxylist) p "Grab: #{url}" doc = get_doc_with_proxy(proxylist,url) show_type = [] _img_url = "http://static.haotv.me/channel/logo/" img_url = _img_url + channel+".jpg" data=doc.css('div[class="mt10 clear"]')[0].content.split(" ") date = data[0] week = data[1] p "Channel: #{channel} Date: #{date} Week: #{week}" @date = "#{week}(#{date})" schedule_list = [] _herf = doc.css("h1[style='float:left']").xpath('img[@src]')[0] img_url = _herf.get_attribute("src") if _herf p "**************IMG: #{img_url}" doc.css('ul[id="pgrow"]')[0].css("li").each do |schedule| _herf= schedule.xpath('a[@href]')[0] schedule_herf=_herf.get_attribute("href") if _herf unless _herf drama =schedule.css('a[class="drama"]')[0] if drama _herfs=drama.get_attribute("href").gsub("/episode/section","#%#") schedule_herf = _herfs.split("#%#")[0] end end if schedule.content.split(" ").size>1 time = schedule.content.split(" ")[0] schedule = schedule.content.split(" ")[1] show_name = "" unless schedule_herf.nil?||schedule_herf.empty? p "Show_infomation:#{schedule_herf} Time:#{time}" show_infomation=get_show_infomation(proxylist,schedule_herf) show_type=show_infomation["type"] show_name = show_infomation["name"] show_img = show_infomation["img"] end p "Time: #{time} schedule: #{schedule} show_infomation_herf: #{schedule_herf} type: #{show_type} name: #{show_name} img:#{show_img}" schedule_list << {"schedule_name"=>schedule,"schedule_logo"=>show_img,"schedule_start"=>time,"show_infomation_herf"=>schedule_herf,"type"=>show_type,"name"=>show_name} end end schedule_list end #获取制定时间和长度url #start_time 为int型 开始时间和今天的差值 正数代表之后的第几天 负数代表之前的第几天 #day_num 为int型 代表抓取的时间从开始时间计算的多少天 def get_assign_date_url(url,start_time,day_num) site="http://www.tvmao.com" if(@site) site=@site end _url = site urls = [] _urls = url.split("-") time = Time.now _wday = time.wday wday = _wday + start_time if wday<0 wday = 1 end end_day = wday + day_num - 1 if end_day>(_wday+7) end_day = _wday + 7 end 0.upto(1).each do |i| _url = _url+"#{_urls[i]}"+"-" end wday.upto(end_day).each do |i| urls << _url+"w#{i}.html" end urls end #获取指定时间段的节目表 def getScheduleAssignDate(channel,herf,proxylist,start_num,day_num=0,img_dir_down_path=@img_down_dir_path) begin day_num = 1 if day_num<1 rescue day_num = 1 end site="http://www.tvmao.com" unless img_dir_down_path img_dir_down_path = __FILE__ end @img_down_file = File.new(File.join(img_dir_down_path,"schedule_img_down_path"),"w+") if(@site) site=@site end _img_url = "http://static.haotv.me/channel/logo/" @show_schedule = {} channel_schedule = {} get_assign_date_url(herf,start_num,day_num).each do |url| @date = "" schedule_list = get_schedulelist_atday(channel,url,proxylist) channel_schedule.merge!({@date=>schedule_list}) unless @date.empty? end @img_down_file.close {"channel_schedule"=>channel_schedule,"show_schedule"=>@show_schedule} end #因原已调用所以保留 #获取一周节目表 def getschedule(channel,herf,proxylist,day_num=7,img_dir_down_path=@img_down_dir_path) p "Day Num is #{day_num}" begin day_num = 1 if day_num<1 rescue day_num = 1 end site="http://www.tvmao.com" unless img_dir_down_path img_dir_down_path = __FILE__ end @img_down_file = File.new(File.join(img_dir_down_path,"schedule_img_down_path"),"w+") if(@site) site=@site end _img_url = "http://static.haotv.me/channel/logo/" @show_schedule = {} get_week_url = lambda {|url,day_num| _url = site urls = [] _urls = url.split("-") 0.upto(1).each do |i| _url = _url+"#{_urls[i]}"+"-" end 1.upto(day_num).each do |i| urls << _url+"w#{i}.html" end urls } channel_schedule = {} get_week_url.call(herf,day_num).each do |url| @date = "" schedule_list = get_schedulelist_atday(channel,url,proxylist) channel_schedule.merge!({@date=>schedule_list}) unless @date.empty? end @img_down_file.close {"channel_schedule"=>channel_schedule,"show_schedule"=>@show_schedule} end #获取节目详细信息 def get_show_infomation(proxy_list,schedule_herf) begin @proxyindex = 0 unless @site @site = "http://www.tvmao.com" end schedule_herf = @site + schedule_herf doc = get_doc_with_proxy(proxy_list,schedule_herf) type = [] name = doc.css('span[itemprop="name"]')[0].content #获取节目的图片 if doc.css('img[class="tvc"]') schedule_img_down_path = doc.css('img[class="tvc"]')[0].get_attribute('src') if doc.css('img[class="tvc"]')[0] end doc.css('span[itemprop="genre"]').each do |_type| type << _type.content end doc.css('a[itemprop="genre"]').each do |_type| type<<_type.content end url = "#{schedule_herf}/detail" doc = get_doc_with_proxy(proxy_list,url) if doc doc.css('span[itemprop="genre"]').each do |_type| type << _type.content end end type.uniq! unless @show_schedule @show_schedule={} end @show_schedule.merge!(name=>get_show_schedule(proxy_list,schedule_herf)) unless @show_schedule.has_key?(name) {"type"=>type,"name"=>name,"img"=>schedule_img_down_path} #rescue => e # p "Error In get_show_infomation msg : #{e.to_s}" end end #获取节目的时间表 def get_show_schedule(proxylist,herf) url = herf + "/playingtime" doc = get_doc_with_proxy(proxylist,url) i = 0 schedule = [] if doc.css('div[id="epg"]')[0] doc.css('div[id="epg"]')[0].css("div[class='c1 col']").each do |epg| unless(i==0) time = epg.css('div[class="f1 fld"]')[0].content channel_name = epg.css('div[class="f2 fld"]')[0].content show_name = epg.css('div[class="f3 fld"]')[0].content times = time.split(" ") week = times[0] date = times[1] _time = times[2] schedule << {"week"=>week,"date"=>date,"time"=>_time,"channel_name"=>channel_name,"show_name"=>show_name} end i += 1 end end schedule end #获取指定访问速度的代理服务器 #time为最慢速度的时间 int型 代表秒 def get_topfast_list(use_time) fast_list = [] time_use = 0 ips_ports = get_proxy_list() ips_ports.each do |ip_port| time_start = Time.now.to_i begin timeout(use_time) do doc = Nokogiri::HTML(open("http://www.tvmao.com/program",:proxy=> "http://#{ip_port}")) end time_end = Time.now.to_i time_use = time_end - time_start p "http://#{ip_port} use_time:#{time_use}" rescue Exception =>e case e when Errno::ETIMEDOUT p "Use http://#{ip_port} timeout" when Timeout::Error p "Use http://#{ip_port} timeout" when Errno::ECONNREFUSED p "Use http://#{ip_port} Error connection" else p "Use http://#{ip_port} Error:#{e.to_s}" end time_use = -1 end if(time_use > 0 &&time_use < 8) fast_list << ip_port end end fast_list end #获取代理列表 def get_proxy_list() list = gg('http://www.proxycn.cn/html_proxy/30fastproxy-1.html') if list.count ==0 list = gg('http://www.proxycn.cn/html_proxy/http-1.html') end ips_ports = [] regex_port = /(?<=<TD class="list">)[0-9]*?(?=<\/TD>)/ regex_ip = /(?<=a href\=whois.php\?whois\=)[0-9,.]*/ list.each do |proxy_txt| port = proxy_txt[regex_port] ip = proxy_txt[regex_ip] if(ip != ""&& !port.to_s.eql?('3128')) port_ip = ip.to_s + ":" + port.to_s ips_ports << port_ip end end p "Count: #{ips_ports.count}" ips_ports end def gg(url) regex_list = /<TD class="list">.*<\/TD>/ href =URI.parse(url) contxt = "" href.open{ |f| f.each_line {|line| contxt =contxt + line + "\n"} } list = contxt.scan(regex_list) end def save_img end end end
require_relative 'hand' class Player include Hand attr_accessor :name, :cards def initialize @cards = [] set_name end def set_name name = '' loop do puts "Tell me your name:" name = gets.chomp break unless name.empty? puts "Sorry, must enter a value" end self.name = name end def show_hand show end end
class Element < ActiveRecord::Base belongs_to :piece has_one :amiante assignable_values_for :nom do ['Sol','Murs','Plafond','Plinthes','Porte','Fenêtre', 'Porte d\'entrée','Fenêtre avec volets'] end end
class IntegerToStringArticles < ActiveRecord::Migration def change change_column :articles, :fb_post_id, :string end end
require_relative "../test_helper" class RestaurantTest < ActiveSupport::TestCase test "a resturant is inactive by defualt" do restaurant = Restaurant.create refute restaurant.active end test "a restaurant is unpublished by default" do restaurant = Restaurant.create refute restaurant.published end test "a restaurant can return it's owner" do user = FactoryGirl.create(:user) role = FactoryGirl.create(:role) restaurant = FactoryGirl.create(:restaurant) job = FactoryGirl.create(:job) user.jobs << job role.jobs << job restaurant.jobs << job assert_equal [user], restaurant.owners end end
class JuggernautObserver < ActiveRecord::Observer observe SpineJuggernautRails.config.observe def after_create(rec) publish(:create, rec) end def after_update(rec) publish(:update, rec) end def after_destroy(rec) publish(:destroy, rec) end protected def publish(type, rec) Juggernaut.publish( SpineJuggernautRails.config.channel, { type: type, id: rec.id, class: "App."+rec.class.name, record: rec }, :except => rec.session_id ) end end
#!/usr/bin/env ruby require 'gli' require 'doing' require 'tempfile' if RUBY_VERSION.to_f > 1.9 Encoding.default_external = Encoding::UTF_8 Encoding.default_internal = Encoding::UTF_8 end include GLI::App version Doing::VERSION wwid = WWID.new program_desc 'A CLI for a What Was I Doing system' default_command :recent sort_help :manually desc 'Output notes if included in the template' default_value true switch [:notes], :default_value => true, :negatable => true # desc 'Wrap notes at X chars (0 for no wrap)' # flag [:w,:wrapwidth], :must_match => /^\d+$/, :type => Integer desc 'Add an entry' arg_name 'entry' command :now do |c| c.desc 'Section' c.arg_name 'section_name' c.default_value wwid.current_section c.flag [:s,:section] c.desc "Edit entry with #{ENV['EDITOR']}" c.switch [:e,:editor] # c.desc "Edit entry with specified app" # c.arg_name 'editor_app' # c.default_value wwid.config.has_key?('editor_app') && wwid.config['editor_app'] ? wwid.config['editor_app'] : false # c.flag [:a,:app] c.action do |global_options,options,args| if options[:e] || (args.length == 0 && STDIN.stat.size == 0) input = "" input += args.join(" ") if args.length > 0 input = wwid.fork_editor(input) if input title, note = wwid.format_input(input) wwid.add_item(title.cap_first, options[:s].cap_first, {:note => note}) wwid.write(wwid.doing_file) else raise "No content" end else if args.length > 0 title, note = wwid.format_input(args.join(" ")) wwid.add_item(title.cap_first, options[:s].cap_first, {:note => note}) wwid.write(wwid.doing_file) elsif STDIN.stat.size > 0 title, note = wwid.format_input(STDIN.read) wwid.add_item(title.cap_first, options[:s].cap_first, {:note => note}) wwid.write(wwid.doing_file) else raise "You must provide content when creating a new entry" end end end end desc 'Add an item to the Later section' arg_name 'entry' command :later do |c| c.desc "Edit entry with #{ENV['EDITOR']}" c.switch [:e,:editor] c.desc "Edit entry with specified app" c.arg_name 'editor_app' c.default_value wwid.config.has_key?('editor_app') && wwid.config['editor_app'] ? wwid.config['editor_app'] : false c.flag [:a,:app] c.action do |global_options,options,args| if options[:e] || (args.length == 0 && STDIN.stat.size == 0) input = "" input += args.join(" ") if args.length > 0 input = wwid.fork_editor(input) if input title, note = wwid.format_input(input) wwid.add_item(title.cap_first, "Later", {:note => note}) wwid.write(wwid.doing_file) else raise "No content" end else if args.length > 0 title, note = wwid.format_input(args.join(" ")) wwid.add_item(title.cap_first, "Later", {:note => note}) wwid.write(wwid.doing_file) elsif STDIN.stat.size > 0 title, note = wwid.format_input(STDIN.read) wwid.add_item(title.cap_first, "Later", {:note => note}) wwid.write(wwid.doing_file) else raise "You must provide content when creating a new entry" end end end end desc 'Add a completed item with @done(date)' arg_name 'entry' command :done do |c| c.desc 'Immediately archive the entry' c.switch [:a,:archive], :negatable => true c.desc 'Section' c.default_value wwid.current_section c.flag [:s,:section], :default_value => wwid.current_section c.desc "Edit entry with #{ENV['EDITOR']}" c.switch [:e,:editor] # c.desc "Edit entry with specified app" # c.arg_name 'editor_app' # c.default_value wwid.config.has_key?('editor_app') && wwid.config['editor_app'] ? wwid.config['editor_app'] : false # c.flag [:a,:app] c.action do |global_options,options,args| if options[:e] || (args.length == 0 && STDIN.stat.size == 0) input = "" input += args.join(" ") if args.length > 0 input = wwid.fork_editor(input) if input title, note = wwid.format_input(input) title += " @done(#{Time.now.strftime('%F %R')})" section = options[:a] ? "Archive" : options[:s] wwid.add_item(title.cap_first, section.cap_first, {:note => note}) wwid.write(wwid.doing_file) else raise "No content" end else if args.length > 0 title, note = wwid.format_input(args.join(" ")) title += " @done(#{Time.now.strftime('%F %R')})" section = options[:a] ? "Archive" : options[:s] wwid.add_item(title.cap_first, section.cap_first, {:note => note}) wwid.write(wwid.doing_file) elsif STDIN.stat.size > 0 title, note = wwid.format_input(STDIN.read) title += " @done(#{Time.now.strftime('%F %R')})" section = options[:a] ? "Archive" : options[:s] wwid.add_item(title.cap_first, section.cap_first, {:note => note}) wwid.write(wwid.doing_file) else raise "You must provide content when creating a new entry" end end end end desc 'List all entries' arg_name 'section' command :show do |c| c.action do |global_options,options,args| if args.length > 0 if wwid.sections.include? args.join(" ").cap_first section = args.join(" ").cap_first else raise "No such section: #{args.join(" ")}" end else section = wwid.current_section end puts wwid.list_section({:section => section, :count => 0}) end end desc 'List recent entries' default_value 10 arg_name 'count' command :recent do |c| c.desc 'Section' c.default_value wwid.current_section c.flag [:s,:section] c.action do |global_options,options,args| unless global_options[:version] if args.length > 0 count = args[0].to_i else count = 10 end puts wwid.recent(count,options[:s].cap_first) end end end desc 'List entries from today' command :today do |c| c.action do |global_options,options,args| puts wwid.today.strip end end desc 'Show the last entry' command :last do |c| c.action do |global_options,options,args| puts wwid.last.strip end end desc 'List sections' command :sections do |c| c.action do |global_options,options,args| puts wwid.sections.join(", ") end end desc 'Select a section to display from a menu' command :choose do |c| c.action do |global_options,options,args| section = wwid.choose_section puts wwid.list_section({:section => section.cap_first, :count => 0}) end end desc 'Add a new section to the "doing" file' arg_name 'section_name' command :add_section do |c| c.action do |global_options,options,args| unless wwid.sections.include?(args[0]) wwid.add_section(args[0].cap_first) wwid.write(wwid.doing_file) else raise "Section #{args[0]} already exists" end end end desc 'Display a user-created view' arg_name 'view_name' command :view do |c| c.desc 'Section' c.flag [:s,:section] c.desc 'Count to display' c.flag [:c,:count], :must_match => /^\d+$/, :type => Integer c.action do |global_options,options,args| if args.empty? title = wwid.choose_view else title = args[0] end view = wwid.get_view(title) if view template = view.has_key?('template') ? view['template'] : nil format = view.has_key?('date_format') ? view['date_format'] : nil count = options[:c] ? options[:c] : view.has_key?('count') ? view['count'] : 10 section = options[:s] ? options[:s].cap_first : view.has_key?('section') ? view['section'] : wwid.current_section order = view.has_key?('order') ? view['order'] : "asc" puts wwid.list_section({:section => section, :count => count, :template => template, :format => format, :order => order }) else raise "View #{title} not found in config" end end end desc 'List available custom views' command :views do |c| c.action do |global_options,options,args| puts wwid.views.join(", ") end end desc 'Move all but the most recent 5 entries in a section to Archive' arg_name 'section' default_value wwid.current_section command :archive do |c| c.desc 'Count to keep' c.default_value 5 c.flag [:k,:keep], :default_value => 5, :must_match => /^\d+$/, :type => Integer c.action do |global_options,options,args| if args.length > 0 section = args.join(" ").cap_first else section = wwid.current_section end wwid.archive(section,options[:k]) end end desc 'Open the "doing" file in an editor (OS X)' command :open do |c| c.desc 'open with app name' c.arg_name 'app_name' c.flag [:a] c.desc 'open with app bundle id' c.arg_name 'bundle_id' c.flag [:b] c.desc 'open with $EDITOR' c.switch [:e], :negatable => false c.action do |global_options,options,args| params = options.dup params.delete_if { |k,v| k.class == String || v.nil? || v == false } if params.length < 2 if options[:a] system %Q{open -a "#{options[:a]}" "#{File.expand_path(wwid.doing_file)}"} elsif options[:b] system %Q{open -b "#{options[:b]}" "#{File.expand_path(wwid.doing_file)}"} elsif options[:e] system %Q{$EDITOR "#{File.expand_path(wwid.doing_file)}"} else if wwid.config.has_key?('editor_app') && !wwid.config['editor_app'].nil? system %Q{open -a "#{wwid.config['editor_app']}" "#{File.expand_path(wwid.doing_file)}"} else system %Q{open "#{File.expand_path(wwid.doing_file)}"} end end else raise "The open command takes a single parameter. #{params.length} specified." end end end desc 'Edit the configuration file' command :config do |c| c.desc 'Editor to use' c.default_value ENV['EDITOR'] c.flag [:e,:editor] c.action do |global_options,options,args| system %Q{#{options[:e]} "#{File.expand_path(DOING_CONFIG)}"} end end pre do |global,command,options,args| wwid.config[:include_notes] = false unless global[:notes] if global[:version] puts "doing v" + Doing::VERSION end # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only true end post do |global,command,options,args| # Use skips_post before a command to skip this # block on that command only end on_error do |exception| # Error logic here # return false to skip default error handling true end exit run(ARGV)
# encoding: UTF-8 require 'spec_helper' describe 'Categories' do before(:all) do @categories = Array.new(2) { Category.sham! } end describe "On the categories path" it "listing all categories" do visit categories_path page.should have_selector(".category", :text => "") end it "creates a new category" do visit categories_path click_on "Nowa kategoria" fill_in 'Nazwa', :with => 'Komputery' click_on 'Dodaj Category' current_path.should eq(categories_path) flash_notice!("Utworzono kategorię") end end
class Rental < ApplicationRecord belongs_to :user belongs_to :van validates :start_date, :end_date, presence: true # validates :start_date, :end_date, :price, :status, :photo, presence: true mount_uploader :photo, PhotoUploader end
require 'fluent-logger' require File.expand_path('json_formatter', File.dirname(__FILE__)) module RailsFluentLogging class LogDevice SEVERITY_MAP = %w(DEBUG INFO WARN ERROR FATAL UNKNOWN) class << self def configure yield(config) reconfigure! end def config @config ||= { app_name: 'rails_app', host: nil, port: 24224, level: :debug, debug: false, datetime_format: '%d/%m/%y %H:%M:%S.%L', log_schema: { datetime: [ :datetime, :green ], severity: [ :severity ], tags: [ lambda do |item| parts = %W([#{item[:pid]}:#{item[:uuid]}]) if item[:user_id] parts << %(U##{item[:user_id]}) end other = item.reject {|k, _| [:pid, :uuid, :user_id].include?(k)} unless other.empty? parts << other.to_s end parts.join(' ') end, :white ], message: :message, _other: true } } end def all_instances @all_instances ||= [] end protected def reconfigure! all_instances.each(&:reconfigure!) end end def initialize self.class.all_instances << self reconfigure! end def silence(*args) end def add(severity, tags, message, progname, &block) return true if severity < level log_entity = apply_formatting({ severity: SEVERITY_MAP[severity] || SEVERITY_MAP.last, tags: make_hash(tags), message: (String === message ? message : message.inspect) }) post_to_fluentd(severity, log_entity) or fallback_log << "#{log_entity}\n" end def method_missing(method, *args) fallback_log.send(method, *args) end def reconfigure! clear_options! end private def apply_formatting(entity) entity[:datetime] = Time.now.utc json_formatter.call(entity) end def post_to_fluentd(severity, data) fluentd_connection_configured? && fluentd_client.post(severity, data) end def clear_options! @options = nil @level = nil @fallback_log = nil @fluentd_client = nil @json_formatter = nil @fluentd_connection_configured = nil end def fluentd_connection_configured? if !defined?(@fluentd_connection_configured) || @fluentd_connection_configured.nil? @fluentd_connection_configured = !(options[:host].nil? || options[:host].empty?) end @fluentd_connection_configured end def options @options ||= {}.merge(self.class.config).tap do |options| if options[:uri] uri = URI.parse options[:uri] options[:host] = uri.host options[:port] = uri.port options[:app_name] = uri.path.sub(/\A\/+/, '').gsub(/\/+/, '.') end end end def level @level ||= ::Logger.const_get(options[:level].to_s.upcase.to_sym) end def fluentd_client @fluentd_client ||= Fluent::Logger::FluentLogger.open(options[:app_name], options) end def json_formatter @json_formatter ||= JsonFormatter.new(options[:log_schema], options[:datetime_format]) end def fallback_log @fallback_log ||= ::Logger.new($stdout) end def make_hash(tags) {}.tap do |tags_hash| tags.each_with_index do |tag, i| if tag.is_a? Hash tags_hash.merge!(tag) else tags_hash[i] = tag end end end end end end
class Engine def initialize #TODO must be provided from config @url = 'http://54.148.156.110:4567/sync-module/converters' end def converters ids ids.map do |i| body = RestClient.get "#{@url}/#{i}" JSON.parse body, symbolize_names: true end end def process input, converters_names, request_id converters_names.map do |name| klass = Object.const_get "#{self.class.name}::#{name}" klass = klass.new value = nil rejected = false status = 200 begin value = klass.run input rescue StandardError => e status = 500 rejected = true end { id: request_id, status: status, value: value, rejected: rejected, errors: (e ? [e.message] : false) } end end def run request_body args = request_body[:arguments].map do |r| convs = converters r[:converterIds] evaluate convs process r[:input], (convs.map {|c| c[:name]}), r[:id] end { results: args.flatten } end def evaluate converters converters.each {|c| eval c[:code]} end def test request_body args = request_body[:arguments] evaluate [request_body[:converter]] response = process([args], [request_body[:converter][:name]], 1)[0] response[:result] = response[:value] response.delete(:value) response.delete(:rejected) response.delete(:id) response end end
require 'mocha' module MockedFixtures module Mocks module Mocha def mock_model_with_mocha(model_class, options_and_stubs={}) all_attributes = options_and_stubs.delete(:all_attributes) add_errors = options_and_stubs.delete(:add_errors) if all_attributes schema = MockedFixtures::SchemaParser.load_schema table = model_class.table_name schema[table][:columns].each { |column| options_and_stubs[column[0].to_sym] = nil unless options_and_stubs.has_key?(column[0].to_sym) } end if add_errors errors = [] errors.stubs(:count).returns(0) errors.stubs(:on).returns(nil) options_and_stubs.reverse_merge!(:errors => errors) end options_and_stubs.reverse_merge!( :id => options_and_stubs[:id], :to_param => options_and_stubs[:id].to_s, :new_record? => false ) obj = stub("#{model_class}_#{options_and_stubs[:id]}", options_and_stubs) obj.instance_eval <<-CODE def is_a?(other) #{model_class}.ancestors.include?(other) end def kind_of?(other) #{model_class}.ancestors.include?(other) end def instance_of?(other) other == #{model_class} end def class #{model_class} end CODE obj end end end end Test::Unit::TestCase.send(:include, MockedFixtures::Mocks::Mocha)
class PatientCase < ActiveRecord::Base # time_in_words needs this include ActionView::Helpers::DateHelper def self.possible_statuses ["Pre-Screen","Registered","Checked In","Scheduled","Unscheduled","Preparation","Procedure","Recovery","Discharge","Checked Out"] end def self.complexity_units [1,2,3,4,5,6,7,8,9,10] end def self.severity_table { 0 => "Unremarkable", 1 => "Mild", 2 => "Moderate", 3 => "Severe" } end ANATOMIES = ["ankle", "foot", "hip", "knee"] @patient_case_join = 'left outer join `trips` ON `trips`.`id` = `patient_cases`.`trip_id` left outer join `patients` ON `patients`.`id` = `patient_cases`.`patient_id` left outer join `risk_factors` ON `risk_factors`.`patient_id` = `patients`.`id`' before_create :set_pre_screen after_save :sync_bilateral, :set_appointment after_create :send_email_alert belongs_to :patient belongs_to :appointment belongs_to :trip belongs_to :disease belongs_to :approved_by, :class_name => "User", :foreign_key => "approved_by_id" belongs_to :created_by, :class_name => "User", :foreign_key => "created_by_id" has_one :operation, :dependent => :destroy has_many :xrays, :dependent => :destroy has_many :physical_therapies, :dependent => :destroy has_one :bilateral_case, :class_name => "PatientCase", :foreign_key => "bilateral_case_id" validates_presence_of :patient validates_presence_of :trip validates_inclusion_of :status, :in => self.possible_statuses, :allow_nil => true validates_numericality_of :severity validates_inclusion_of :severity, :in => self.severity_table.keys validates_inclusion_of :anatomy, :in => ANATOMIES + [nil] accepts_nested_attributes_for :patient accepts_nested_attributes_for :xrays, :allow_destroy => true, :reject_if => proc { |attributes| attributes['photo'].blank? } delegate :complexity_minutes, :to => :trip delegate :name, :to => :patient delegate :primary_surgeon, :to => :operation, :allow_nil => true delegate :secondary_surgeon, :to => :operation, :allow_nil => true scope :authorized, includes([:patient, :trip]).where("patient_cases.approved_at is not ?", nil) scope :unauthorized, includes([:patient, :trip]).where("patient_cases.approved_at is ?", nil) scope :scheduled, where("patient_cases.appointment_id is not ?", nil) scope :unscheduled, where("patient_cases.appointment_id is ?", nil) scope :future, includes([:trip]).where("trips.start_date IS NULL OR (trips.start_date > ? AND (trips.end_date IS NULL OR trips.end_date > ?))", Time.zone.now, Time.zone.now) scope :search, Proc.new { |term| query = term.strip if query.present? { :include => [:patient], :conditions => [name_full_query_fragment, "%#{query}%"] } end } scope :anatomy, lambda { |name| if name.present? { :conditions => ["lower(anatomy) in (?)",Array(name).map(&:downcase)] } end } scope :male, :include => :patient, :conditions => ["patients.male = ?", true] scope :female, :include => :patient, :conditions => ["patients.male = ?", false] scope :bilateral, :conditions => ["patient_cases.bilateral_case_id is not ?", nil] def to_s "Case ##{id}" end def as_json(options={}) { :id => self.id, :to_s => self.to_s, :status => self.status, :photo => self.patient.displayed_photo(:tiny), :patient => self.patient.to_s, :location => self.location, :anatomy => self.anatomy, :time_in_words => self.time_in_words, :revision => self.revision? } end def authorize!(approved_by_id = nil) self.update_attributes(:approved_by_id => approved_by_id, :approved_at => Time.now, :status => "Registered") true end def deauthorize! self.update_attributes(:approved_by_id => nil, :approved_at => nil, :status => "Pre-Screen") true end def authorized? !approved_at.blank? end def treated? operation.present? end def in_facility? ["Checked In","Preparation","Procedure","Recovery","Discharge"].include?(status) end # This only works for MySQL...and ergo not Heroku def self.order(ids) return if ids.blank? update_all( ['schedule_order = FIND_IN_SET(id, ?)', ids.join(',')], { :id => ids } ) end def time_in_words # TODO - see if using partials instead of JSON objects improves performance and kludges like this one return "Time Unknown" if complexity.blank? str = distance_of_time_in_words(Time.now, Time.now + (complexity_minutes * complexity.to_i).to_i.minutes, false, { :two_words_connector => ", " }) return str.blank? ? "Time Unknown" : str end def display_xray return nil if xrays.empty? return xrays.first if (xrays.size == 1) || (xrays.all?{ |x| !x.primary? }) return xrays.select{ |x| x.primary == true }.first end def operation_display_xray return nil if xrays.empty? return xrays.select{ |x| x.primary == true && x.operation_id.present? }.first end def diagnosis_display_xray return nil if xrays.empty? return xrays.select{ |x| x.primary == true && !x.operation_id.present? }.first end def related_untreated_cases patient.patient_cases.select{ |c| c.operation.nil? } - [self] end def self.group_cases(patient_cases) raise "Invalid cases." unless patient_cases.is_a?(Array) raise "Only cases may be grouped." unless patient_cases.all?{ |pc| pc.is_a?(PatientCase) } raise "All grouped cases must be authorized." unless patient_cases.all?{ |pc| pc.authorized? } raise "All grouped cases must belong to the same trip." if patient_cases.map(&:trip_id).uniq.compact.size > 1 trip_id = patient_cases.map(&:trip_id).uniq.first # Try to find the first relevant case group from cases. We're bundling them together, so it doesn't really matter which is which. # If we don't have a valid ID, then no case groups existed. Make one. appointment_id = patient_cases.map(&:appointment_id).uniq.compact.first || Appointment.create(:trip_id => trip_id).try(:id) # Make single case group applicable to all cases patient_cases.each{ |pc| pc.update_attributes(:appointment_id => appointment_id) } # Destroy any case groups orphaned by this action Appointment.remove_orphans(trip_id) # Deliberately join bilaterals if relevant patient_cases.first.appointment.join_bilateral_cases end def authorize=(val) self.approved_at = val.to_i.zero? ? nil : Time.now end def authorize authorized? end private ##################################################################### def set_appointment if self.authorized? self.update_column(:appointment_id, Appointment.create(:trip_id => self.trip_id).try(:id)) unless self.appointment.present? else self.appointment.remove(self) if self.appointment.present? end end def sync_bilateral bilateral_case.update_attribute(:bilateral_case_id, self.id) if bilateral_case.present? && bilateral_case.bilateral_case_id != self.id end def set_pre_screen status = "Pre-Screen" end def send_email_alert if created_by.present? && created_by.has_role?("liaison") emails = trip.alert_users.map(&:email).compact.uniq Mailer.case_added(self,emails).deliver end end def self.name_full_query_fragment if connection_config[:adapter] == "postgresql" "patients.name_full ILIKE ?" else "patients.name_full like ?" end end end
class UserValidator < ActiveModel::Validator def validate(record) record.errors.add :base, "Password should be reverse of email" unless password.eql?(email.reverse) end end
require 'securerandom' # Model representing the result message posted to Kinesis stream about everything that has gone on here -- good, bad, or otherwise. class RequestResult require 'aws-sdk' require_relative './sierra_request.rb' require_relative './hold_request.rb' # Sends a JSON message to Kinesis after encoding and formatting it. def self.send_message(json_message) message = Stream.encode(json_message) client = Aws::Kinesis::Client.new resp = client.put_record({ stream_name: ENV["HOLD_REQUEST_RESULT_STREAM"], data: message, partition_key: SecureRandom.hex(20) }) return_hash = {} if resp.successful? return_hash["code"] = "200" return_hash["message"] = json_message, resp $logger.info "Message sent to HoldRequestResult #{json_message}, #{resp}" else return_hash["code"] = "500" return_hash["message"] = json_message, resp $logger.error "FAILED to send message to HoldRequestResult #{json_message}, #{resp}." end return_hash end def self.handle_success(hold_request, type) $logger.info "Hold request successfully posted. HoldRequestId: #{hold_request["data"]["id"]}. JobId: #{hold_request["data"]["jobId"]}" message_result = RequestResult.send_message({"jobId" => hold_request["data"]["jobId"], "success" => true, "holdRequestId" => hold_request["data"]["id"].to_i}) {"code" => message_result["code"], "type" => type, "message" => message_result["message"]} end def self.handle_500_as_error(hold_request, message, message_hash, type) $logger.error "Request errored out. HoldRequestId: #{hold_request["data"]["id"]}. JobId: #{hold_request["data"]["jobId"]}. Message Name: #{message_hash["message"]}. ", "error_codename" => "HIGHLIGHTER" message_result = RequestResult.send_message({"jobId" => hold_request["data"]["jobId"], "success" => false, "error" => { "type" => "hold-request-error", "message" => message }, "holdRequestId" => hold_request["data"]["id"].to_i}) {"code" => "500", "type" => type} end # Get list of phrases we anticipate in error messages where request has # already been sent. Note "Your request has already been sent" is a # possible error message, but not one we handle here. def self.already_sent_errors ["already on hold for or checked out to you"] end def self.retryable_errors ["Your request has already been sent"] end def self.timeout_errors ["Timeout"] end def self.possible_item_suppressed_errors ['This record is not available'] end def self.is_error_type?(message_hash, error_list) hash = JSON.parse(message_hash["message"]) (hash.is_a? Hash) && (hash["description"].is_a? String) && error_list.any? {|error| hash["description"].include?(error)} end # Get holds for patron id via Sierra api def self.get_patron_holds(patron) begin sierra_request = SierraRequest.new({}) sierra_request.base_request_url = ENV['SIERRA_URL'] sierra_request.assign_bearer sierra_request.get_holds(patron) rescue StandardError => e $logger.error "Unable to get holds for patron: #{e.message}" end end # Returns true if hold_request hash is for a record for which the patron has # already placed a hold def self.patron_already_has_hold?(hold_request) # Get patron id: patron = hold_request["data"]["patron"] record = hold_request["data"]["record"] # Fetch holds from Sierra api for patron id: holds = self.get_patron_holds(patron) (holds.is_a? Hash) && holds["entries"] && (holds["entries"].is_a? Array) && holds["entries"].any? do |entry| (entry.is_a? Hash) && (entry['record'].is_a? String) && entry['record'].include?(record) end end # Return true if hold_request hash and message_hash (response from Sierra # NCIP/Rest api): # 1) is not an "already sent" error (which we don't consider an error?) OR # 2) hold is not a duplicate for patron # This is called in the context of handling an error after checking for other # known error conditions. This method asserts that the hold_request and # message_hash pair don't represent a known condition that we prefer to # ignore as non-error (i.e. "already sent" error or duplicate hold request). # This method returns true if the error is unrecognized - an "actual error". def self.is_actually_error?(hold_request, message_hash) !self.is_error_type?(message_hash, self.already_sent_errors) || !self.patron_already_has_hold?(hold_request) end def self.there_is_time(timestamp) Time.now.to_f - timestamp.to_f < 30 end def self.handle_retryable_error(json_data, hold_request, type, timestamp) if self.there_is_time(timestamp) $logger.info "Encountered retryable exception" sleep(10) HoldRequest.new.route_request_with(json_data,hold_request, timestamp) else $logger.error "Request errored out. HoldRequestId: #{hold_request["data"]["id"]}. JobId: #{hold_request["data"]["jobId"]}. Message Name: Request timed out. ", "error_codename" => "HIGHLIGHTER" message_result = RequestResult.send_message({"jobId" => hold_request["data"]["jobId"], "success" => false, "error" => { "type" => "hold-request-error", "message" => "Request timed out" }, "holdRequestId" => hold_request["data"]["id"].to_i}) {"code" => "500", "type" => type} end end def self.handle_500(hold_request, json_data, message, message_hash, type, timestamp) $logger.info "Received 500 response. Checking error. Message: #{message}" if self.is_error_type?(message_hash, self.retryable_errors) handle_retryable_error(json_data, hold_request, type, timestamp) elsif self.is_error_type?(message_hash, self.timeout_errors) self.handle_timeout(type, json_data, hold_request, timestamp) elsif self.is_actually_error?(hold_request, message_hash) self.handle_500_as_error(hold_request, message, message_hash, type) else self.handle_success(hold_request, type) end end def self.handle_timeout(type, json_data, hold_request, timestamp) if there_is_time(timestamp) $logger.error "HoldRequestId: #{hold_request["data"]["id"]}. JobId: #{hold_request["data"]["jobId"]}. Message Name: Hold request timeout out. Will retry. ", "error_codename" => "HIGHLIGHTER" HoldRequest.new.route_request_with(json_data,hold_request, timestamp) else $logger.error "Request errored out. HoldRequestId: #{hold_request["data"]["id"]}. JobId: #{hold_request["data"]["jobId"]}. Message Name: Request timed out. Will not retry. ", "error_codename" => "HIGHLIGHTER" message_result = RequestResult.send_message({"jobId" => hold_request["data"]["jobId"], "success" => false, "error" => { "type" => "hold-request-error", "message" => "Request timed out" }, "holdRequestId" => hold_request["data"]["id"].to_i}) {"code" => "500", "type" => type} end end # Crafts a message to post based on all available information. def self.process_response(message_hash,type=nil,json_data=nil,hold_request=nil, timestamp=nil) if json_data == nil || hold_request == nil || hold_request["data"] == nil $logger.error "Hold request failed. Key information missing or hold request data not found." message_result = RequestResult.send_message({"jobId" => "", "success" => false, "error" => { "type" => "key-information-missing", "message" => "500: Hold request failed. Key information missing or hold request data not found" }, "holdRequestId" => json_data["trackingId"].to_i}) { "code" => "500", "type" => type } elsif message_hash["code"] == nil message_result = RequestResult.send_message({"jobId" => hold_request["data"]["jobId"], "success" => false, "error" => { "type" => "recap-hold-request-consumer-error", "message" => "500: ReCAP hold request consumer failure. Valid response code not found." }, "holdRequestId" => hold_request["data"]["id"].to_i}) { "code" => "500", "type" => type } elsif message_hash["code"] == "200" || message_hash["code"] == "204" self.handle_success(hold_request, type) elsif message_hash["code"] == "404" $logger.info "Request returned 404. HoldRequestId: #{hold_request["data"]["id"]}. JobId: #{hold_request["data"]["jobId"]}" message_result = RequestResult.send_message({"jobId" => hold_request["data"]["jobId"], "success" => false, "error" => { "type" => "hold-request-not-found", "message" => "404: Hold request not found or deleted. Please try again." }, "holdRequestId" => hold_request["data"]["id"].to_i}) {"code" => "404", "type" => type} else begin # Did it fail because the record is suppressed? # e.g. {"code"=>132, "specificCode"=>2, "httpStatus"=>500, "name"=>"XCirc error", "description"=>"XCirc error : This record is not available"} if self.is_error_type?(message_hash, self.possible_item_suppressed_errors) && hold_request['data']['deliveryLocation'] && SierraRequest::HOLD_OPTIONAL_STAFF_LOCATIONS.include?(hold_request['data']['deliveryLocation']) $logger.info "Detected hold request failure at staff-only location; Quietly swallowing the error. JobId: #{hold_request["data"]["jobId"]}" return self.handle_success(hold_request, type) end j = JSON.parse(message_hash["message"]) message = "#{j["httpStatus"]} : #{j["description"]}" rescue Exception => e message = "500: recap hold request error. #{message_hash}: #{e.message}" end self.handle_500(hold_request, json_data, message, message_hash, type, timestamp) end end end
class PostcodeValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) postcode = UKPostcode.parse(value || '') return if postcode.valid? record.errors.add attribute, :invalid_postcode end end
class HomepageController < ApplicationController skip_before_action :require_login before_action :require_login, only: [:notifications, :history] def index categories = ['All','Accessories', 'Books', 'Clothing', 'Electronics', 'Home and Kitchen', 'Luggages and Bags', 'Office Products', 'Sports and Outdoors', 'Tools and Home Improvement', 'Toys and Games', 'Other'] @all_items = Array.new if params[:term] @all_items = Item.where('name LIKE ?', "%#{params[:term]}%") Tag.where('name LIKE ?', "%#{params[:term]}%").each do|tag| @all_items += tag.items.select{|item|!@all_items.include? item} end else @all_items = Item.all end if params[:category] && params[:category] != "" puts "Catergory: " + categories[params[:category].to_i] + " " + params[:category] @all_items = @all_items.select{|item|item.category == categories[params[:category].to_i]} end #remove items that have been reported as stolen puts "number of interactions", Interaction.count @all_items = @all_items.select{ |item| item.interactions.last.blank? || !item.interactions.last.failed? } if current_user if current_user.locked render "locked" end end # @five_star_reviews = find_five_star_reviews # @five_star_review_users = get_five_star_review_users end def history @person = Person.find_by_user_id(current_user.id) @items = @person.items @interactions = Interaction.where(item_id: @items.map(&:id)).order(date: :desc) end ############################################## ##############PRIVATE FUNCTIONS############### ############################################## private # def find_five_star_reviews # five_star_reviews = Review.where(rating: 5.0).last(3) # if five_star_reviews.blank? # return nil # else # return five_star_reviews # end # end # # def get_five_star_review_users # five_star_reviews = find_five_star_reviews # reviewers = [] # if five_star_reviews.blank? # return nil # else # five_star_reviews.each do |review| # interaction = Interaction.find_by_id(review.interaction_id) # person = Person.find_by_id(interaction.person_id) # reviewers.push(person) # end # return reviewers # end # end end
class Plan < ActiveRecord::Base self.inheritance_column = :_type_disabled scope :monthly, -> { where(type: 'monthly', active: true).last } scope :half_yearly, -> { where(type: 'half_yearly', active: true).last } scope :yearly, -> { where(type: 'yearly', active: true).last } def amount units * price end def amount_including_taxes (amount + taxes).to_f end def taxes (amount * Constants::VAT_RATE).to_f end def amount_for(units_delivered) units_delivered * price end def amount_difference(units_delivered) (amount_including_taxes / units) - amount_for(units_delivered) end end
# -*- coding: utf-8 -*- require 'spec_helper' describe RpcController do let(:member) { FactoryBot.create(:member, password: 'mala', password_confirmation: 'mala') } before do member.set_auth_key allow_any_instance_of(Member).to receive(:subscribe_feed).and_return(FactoryBot.create(:subscription)) end describe 'POST /update_feed' do let(:params) { FactoryBot.attributes_for(:item) } it 'renders json' do post :update_feed, { api_key: member.auth_key, json: params.to_json } expect(response.body).to be_json end it 'creates new item' do expect { post :update_feed, { api_key: member.auth_key, json: params.to_json } }.to change { Item.count }.by(1) end context 'Not Feed' do let(:params){FactoryBot.attributes_for(:item).slice(:link, :title, :body, :author, :category, :published_date).merge( feedtitle: 'malamalamala', api_key: member.auth_key, feedlink: 'http://ma.la')} it 'creates new item' do expect { post :update_feed, { api_key: member.auth_key, json: params.to_json } }.to change { Item.count }.by(1) end end context 'JSON-RPC' do let(:params) { FactoryBot.attributes_for(:item).slice(:link, :title, :body, :author, :category, :published_date) } it 'creates new item' do expect { post :update_feed, { api_key: member.auth_key, json: params.to_json } }.to change { Item.count }.by(1) end end context 'Not-Feed ON JSON RPC' do let(:params) { FactoryBot.attributes_for(:item).slice(:link, :title, :body, :author, :category, :published_date).merge( feedtitle: 'malamalamala', feedlink: 'http://ma.la') } it 'creates new item' do expect { post :update_feed, { api_key: member.auth_key, json: params.to_json } }.to change { Item.count }.by(1) end end context 'without guid' do let(:params) { FactoryBot.attributes_for(:item_without_guid) } it 'creates a new item with guid == link' do expect { post :update_feed, { api_key: member.auth_key, json: params.to_json } }.to change { Item.find_by(guid: params[:link]).nil? }.from(true).to(false) end end end end
# -*- mode: ruby -*- # vi: set ft=ruby : VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| # Set vagrant box to ubuntu 14.04.1 with puppet 3.7.2 config.vm.box = 'ubuntu-14.04.1-64bit-vbox-4.3.18-puppet-3.7.2' config.vm.hostname = 'web.vagrant.local' # Set box memory to 1024 config.vm.provider :virtualbox do |vb| vb.customize ['modifyvm', :id, '--memory', '1024'] end # Create extra shared folders for the puppet config.vm.synced_folder "puppet/files", "/etc/puppet/files" config.vm.synced_folder 'hiera', '/etc/puppet/hiera' # Puppet provisioning config.vm.provision :puppet, :options => ['--fileserverconfig=/vagrant/fileserver.conf', '--verbose'] do |puppet| puppet.manifests_path = 'puppet/manifests' puppet.module_path = 'puppet/modules' puppet.hiera_config_path = 'hiera/hiera.yaml' puppet.manifest_file = 'site.pp' end end
Vagrant.configure("2") do |config| config.vm.define "master" do |master| master.vm.box = "debian/stretch64" master.vm.hostname = 'gitlab' master.vm.provision "shell", path: "server.sh" master.vm.network "forwarded_port", guest: 80, host: 81 master.vm.provider :virtualbox do |v| v.customize ["modifyvm", :id, "--memory", 512] v.customize ["modifyvm", :id, "--name", "gitlab"] end end end
class Email < ApplicationRecord VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false } # after_create :send_email def send_email EmailMailer.email_user(self).deliver # send email end end
require_relative "./card_kind.rb" module Model class Pack def initialize @cards = [] reshuffle end def reshuffle_if_necessary return if @cards.count > 2 reshuffle end def draw reshuffle_if_necessary @cards.pop end private def reshuffle puts "RESHUFFLING" @cards = 4.times.map {|_| CardKind::KINDS_SET}.flatten @cards.shuffle! end end end
module Sinatra module CMS module Application module Helpers def placeholder "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in tempor lacus. Suspendisse fermentum aliquam magna, vitae condimentum ante adipiscing nec. Phasellus hendrerit lacinia congue." end def page_path env['PATH_INFO'] end def cms_field tag, field_name, options={} attributes = options.collect { |key, value| "#{key}=\"#{value}\"" }.join(' ') text = requested_page && requested_page[field_name] ? requested_page[field_name] : placeholder <<-HTML <#{tag} data-page-element data-cms-name="#{field_name}" #{attributes}>#{text}</#{tag}> HTML end def enable_cms "<script type='text/javascript' src='http://#{env['HTTP_HOST']}#{env['SCRIPT_NAME']}/cms-assets/js/sinatra-cms/editor.js'></script>" if params[:editor] end end end end end
class Company < ActiveRecord::Base has_many :passports validates :name, :city, :address, :country, presence: true end
FactoryBot.define do factory(:nav_item) do title_sv title_en trait :menu do nav_item_type 'menu' end trait :page do nav_item_type 'page' page end trait :link do nav_item_type 'link' link end end end
FactoryGirl.define do sequence(:ldap_uid) { |n| "ldap#{n}@musc.edu" } factory :identity do email 'email@musc.edu' # need this for fake data ldap_uid sequence(:first_name) { |n| "Sally-#{n}"} last_name "Smith" password "password" password_confirmation "password" time_zone "Eastern Time (US & Canada)" trait :with_counter do after :create do |identity| create(:identity_counter, identity: identity) end end factory :identity_with_counter, traits: [:with_counter] end end
module Vocabulary class Concept < ApplicationRecord self.inheritance_column = :_type_disabled TYPES = %w(Concept Collection) # searchkick # has paper trail include AttrJson::Record include AttrJson::NestedAttributes include AttrJson::Record::QueryScopes attr_json_config(default_container_attribute: :data) attr_json :labels, Label.to_type, array: true, rails_attribute: true, accepts_nested_attributes: { reject_if: proc { |attributes| attributes['body'].blank? } } attr_json :notes, Note.to_type, array: true, rails_attribute: true, accepts_nested_attributes: { reject_if: proc { |attributes| attributes['body'].blank? } } belongs_to :creator, class_name: 'User' belongs_to :profile, counter_cache: true # has_many :references, as: :referenceable has_many :states, dependent: :destroy has_many :relationships, dependent: :destroy has_many :local_concepts, as: :inverseable, through: :relationships, dependent: :destroy, source: :inversable, source_type: 'Vocabulary::Concept' has_many :narrower_concepts, -> { merge(Vocabulary::Relationship.narrower) }, as: :inverseable, through: :relationships, dependent: :destroy, source: :inversable, source_type: 'Vocabulary::Concept' has_many :broader_concepts, -> { merge(Vocabulary::Relationship.broader) }, as: :inverseable, through: :relationships, dependent: :destroy, source: :inversable, source_type: 'Vocabulary::Concept' has_many :close_concepts, -> { merge(Vocabulary::Relationship.close) }, as: :inverseable, through: :relationships, dependent: :destroy, source: :inversable, source_type: 'Vocabulary::Concept' has_many :exact_concepts, -> { merge(Vocabulary::Relationship.exact) }, as: :inverseable, through: :relationships, dependent: :destroy, source: :inversable, source_type: 'Vocabulary::Concept' has_many :related_concepts, -> { merge(Vocabulary::Relationship.related) }, as: :inverseable, through: :relationships, dependent: :destroy, source: :inversable, source_type: 'Vocabulary::Concept' def root? self.in?(self.class.roots) end scope :roots, -> { relationships = Vocabulary::Relationship.arel_table concepts = Vocabulary::Concept.arel_table where( Vocabulary::Relationship \ .where(relationships[:concept_id].eq(concepts[:id])) \ .where(relationships[:type].eq('broader')) \ .exists .not ) } attr_accessor :current_state validates :type, :creator, :labels, presence: true accepts_nested_attributes_for :relationships, allow_destroy: true, reject_if: proc { |attributes| attributes['foreign_concept'].blank? } accepts_nested_attributes_for :states, reject_if: :all_blank, allow_destroy: true def current_state states.order(created_at: :desc).first.try(:type) || 'Unstable' end def current_state=(params) self.states.build(params) unless params[:type] == current_state end # after_commit :reindex_concept # # # surpress double entries in search, only show the original # def should_index? # !matches.where(associatable_type: "Vocab::Concept", property: "exact").exists? # end # # def search_data # { # broader: broader_concepts.map{|b| b.labels.map(&:body).join(' ') }, # narrower: narrower_concepts.map{|n| n.labels.map(&:body).join(' ') }, # scheme: scheme.title, # labels: labels.map(&:body), # notes: notes.map(&:body), # matches: matches.map{|m| [m.property, m.associatable.try(:name)] } # } # end # # def reindex_concept # concept.reindex # end def preferred_label(lang=nil) labels.select{ |l| l.type == 'Preferred' and l.lang == lang and l.abbr == false }.first.presence || labels.select{ |l| l.type == 'Preferred' and l.abbr == false }.first end def name(lang=nil) type == 'Collection' ? "<#{preferred_label(lang).try(:body)}>" : preferred_label(lang).try(:body) end def definition(lang=nil) notes.select{ |n| n.type == 'Definition' and n.lang == lang }.first.try(:body).presence || notes.select{ |n| n.type == 'Definition' }.first.try(:body) end # def indent # ancestor_links.first ? (ancestor_links.first.distance.to_i+1)*17 : 20 # end # # def contributors # [creator].concat(labels.map(&:creator)).concat(notes.map(&:creator)).flatten.uniq # end # # # def self.sorted_by(sort_option) # direction = ((sort_option =~ /desc$/) ? 'desc' : 'asc').to_sym # case sort_option.to_s # when /^updated_at_/ # { updated_at: direction } # else # raise(ArgumentError, "Invalid sort option: #{ sort_option.inspect }") # end # end # # def self.options_for_sorted_by # [ # ['Updated asc', 'updated_at_asc'], # ['Updated desc', 'updated_at_desc'] # ] # end end end
# initializeメソッド =begin class Drink def initialize puts "新しいオブジェクト" end end Drink.new # インスタンス変数の初期値を設定する class Drink def initialize @name = "カフェラテ" end def name @name end end drink = Drink.new puts drink.name =end # initializeメソッドへ引数を渡す class Drink def initialize(name) @name = name end def name @name end end drink = Drink.new("モカ") puts drink.name
App0922::Application.routes.draw do resources :payments root to: 'payments#index' end
class Search def initialize(query) @raw_query = query end def sanitize(raw_query) raw_query.gsub!(/ë/, 'e') raw_query.gsub!(/ö/, 'o') raw_query.gsub!(/ğ/, 'g') raw_query.gsub!(/Ö/, 'O') raw_query.split.map(&:capitalize).join(' ').strip end def search sanitized_query = sanitize(@raw_query) @result = Subject.where("name LIKE ?", "%#{sanitized_query}%").limit(1)[0] end end
class Channel < ActiveRecord::Base belongs_to :user has_many :posts def owned_by(user) return self.user_id==user.id end end
#!/usr/bin/env ruby #Just a simple example command. # @param <random> - Random Parameter 1 # @param - Random Parameter 2 def result(foo) # @param <foo> puts "It worked! 🎩✨ " + foo end result(ARGV.join(" "))
require 'player' describe Player do let(:player) { Player.new } describe "#recieve_card" do it "recieves a card, and puts the card in its hand" do new_card = instance_double("Card", :suit => :S, :value => 14) player.recieve_card(new_card) expect(player.hand_size).to eq(1) end end describe "#discard" do it "drops card at an index" do end end describe "#bet" do it "can choose to see, raise, or fold" do end it "returns raise_value with raise" do end end end
class MoviesController < ApplicationController def index @movies = Movie.all end def movie_params movie_params = params.require(:movie).permit(:title, :description, :rating, :released_on, :total_grossm, :cast, :director, :duration, :inmage) end def show @movie = Movie.find(params[:id]) end def new @movie = Movie.new end def update movie_params = params.require(:movie).permit(:title, :description, :rating, :released_on, :total_grossm, :cast, :director, :duration, :inmage) @movie = Movie.find(params[:id]) if @movie.update(movie_params) redirect_to @movie, notice: "Movie successfully updated!" else render :edit end end def edit @movie = Movie.find(params[:id]) end def image_for(movie) if movie.image_file_name.blank? image_tag('placeholder.png') else image_tag(movie.image_file_name) end end def create @movie = Movie.new(movie_params) movie_params = params.require(:movie).permit(:title, :description, :rating, :released_on, :total_grossm,:cast, :director, :duration, :inmage) if @movie.save redirect_to @movie, notice: "Movie successfully created!" else render :new end end def destroy @movie = Movie.find(params[:id]) @movie.destroy redirect_to movies_url, alert: "Movie successfully deleted!" end def vali validates :title, :released_on, :duration, presence: true validates :description, length: { minimum: 25 } validates :total_gross, numericality: { greater_than_or_equal_to: 0 } validates :inmage, allow_blank: true, format: { with: /\w+\.(gif|jpg|png)\z/i, message: "must reference a GIF, JPG, or PNG image" } end end
require 'test_helper' class HTMLTest < Curtain::TestCase class ::HTMLView < Curtain::View end def use(lang) HTMLView.template_directories File.join(File.dirname(__FILE__), "examples", "html", lang) end %w[erb slim].each do |lang| test "void tag with #{lang}" do use lang assert_equal '<br>', render(:void_tag) end test "void tag with attributes with #{lang}" do use lang assert_equal %{<img src="/logo.png" alt="Logo">}, render(:void_tag_with_attributes) end test "content tag with #{lang}" do use lang assert_equal %{<p></p>}, render(:content_tag) end end protected def render(*args) strip_lines(HTMLView.new.render(*args)) end end
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception def bool(name, default=nil) p = params[name] return default.nil? ? nil : default if p.nil? %w(1 on o true t yes y).include? p.to_s end def int(name, default=nil) p = params[name] return default.nil? ? nil : default if p.nil? p.to_i end end
# frozen_string_literal: true class Monologue::PostsController < Monologue::ApplicationController def index @page = params[:page].nil? ? 1 : params[:page] @posts = posts_for_site.page(@page) .includes(:user, :tags) .published end def show if monologue_current_user @post = posts_for_site.default.where(url: params[:post_url]).first else @post = posts_for_site.published.where(url: params[:post_url]).first end not_found if @post.nil? end def feed @posts = posts_for_site.published.limit(25) if params[:tags].present? tags = params[:tags].split(',') tag_ids = Monologue::Tag.where(:name_downcase.in => tags).pluck(:id) @posts = @posts.where(:tag_ids.in => tag_ids) end render 'feed', layout: false end end
require_relative './dance_module.rb' require_relative './class_methods_module.rb' require_relative './fancy_dance.rb' class Kid #include lets us use all the dance module methods #as instance methods that only the newly created obj can access include Dance #including a CLASS method here with the keyword extend #extend MetaDancing extend FancyDance::ClassMethods include FancyDance::InstanceMethods attr_accessor :name def initialize(name) @name = name end end
class CreateExoticPlants <ActiveRecord::Migration def change create_table :plants do |t| t.string :name t.text :description t.timestamps end end end
# frozen_string_literal: true require 'spec_helper' require 'bolt_spec/conn' require 'bolt_spec/files' require 'bolt_spec/integration' require 'bolt_spec/puppetdb' require 'bolt/catalog' require 'bolt/task' describe "passes parsed AST to the apply_catalog task" do include BoltSpec::Conn include BoltSpec::Files include BoltSpec::Integration include BoltSpec::PuppetDB let(:modulepath) { File.join(__dir__, '../fixtures/apply') } let(:trusted_external) { File.join(__dir__, '../fixtures/scripts/trusted_external_facts.sh') } let(:config_flags) { %W[--format json --targets #{uri} --password #{password} --modulepath #{modulepath}] + tflags } before(:each) do allow(Bolt::ApplyResult).to receive(:from_task_result) { |r| r } allow_any_instance_of(Bolt::Applicator).to receive(:catalog_apply_task) { path = File.join(__dir__, "../fixtures/apply/#{apply_task}") impl = { 'name' => apply_task, 'path' => path } metadata = { 'supports_noop' => true, 'input_method' => 'environment' } Bolt::Task.new('apply_catalog', metadata, [impl]) } end def get_notifies(result) expect(result).not_to include('kind') expect(result[0]).to include('status' => 'success') result[0]['value']['report']['catalog']['resources'].select { |r| r['type'] == 'Notify' } end # SSH only required to simplify capturing stdin passed to the task. WinRM omitted as slower and unnecessary. describe 'over ssh', ssh: true do let(:uri) { conn_uri('ssh') } let(:password) { conn_info('ssh')[:password] } let(:apply_task) { 'apply_catalog.sh' } let(:tflags) { %w[--no-host-key-check] } it 'the catalog include the expected resources' do result = run_cli_json(%w[plan run basic] + config_flags) reports = result[0] expect(reports.count).to eq(5) resources = reports.group_by { |r| r['type'] } expect(resources['File'].count).to eq(2) files = resources['File'].select { |f| f['title'] == '/root/test/hello.txt' } expect(files.count).to eq(1) expect(files[0]['parameters']['content']).to match(/hi there I'm Debian/) end it 'uses trusted facts' do result = run_cli_json(%w[plan run basic::trusted] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) expect(notify[0]['title']).to eq( "trusted {authenticated => local, certname => #{uri}, extensions => {}, "\ "hostname => #{uri}, domain => , external => {}}" ) end it 'uses trusted external facts' do with_tempfile_containing('bolt', YAML.dump("trusted-external-command" => trusted_external), '.yaml') do |conf| result = run_cli_json(%W[plan run basic::trusted --configfile #{conf.path}] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) expect(notify[0]['title']).to eq( "trusted {authenticated => local, certname => #{uri}, extensions => {}, "\ "hostname => #{uri}, domain => , external => {hot => cocoa, pepper => mint}}" ) end end it 'errors if trusted external facts path does not exist' do with_tempfile_containing('bolt', YAML.dump("trusted-external-command" => '/absent.sh'), '.yaml') do |conf| expect { run_cli_json(%W[plan run basic::trusted --configfile #{conf.path}] + config_flags) } .to raise_error(Bolt::FileError, %r{The trusted-external-command '/absent.sh' does not exist}) end end it 'uses target vars' do result = run_cli_json(%w[plan run basic::target_vars] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) expect(notify[0]['title']).to eq('hello there') end it 'plan vars override target vars and respects variables explicitly set to undef' do result = run_cli_json(%w[plan run basic::plan_vars] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) expect(notify[0]['title']).to eq('hello world') logs = @log_output.readlines expect(logs).not_to include(/Unknown variable: 'signature'/) expect(logs).not_to include(/Unknown variable: 'plan_undef'/) expect(logs).to include(/Unknown variable: 'apply_undef'/) expect(logs).to include(/Plan vars set to undef:/) end it 'applies a class from the modulepath' do result = run_cli_json(%w[plan run basic::class] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) end it 'allows and warns on language violations (strict=warning)' do result = run_cli_json(%w[plan run basic::strict] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) expect(notify[0]['parameters']['message']).to eq('a' => 2) logs = @log_output.readlines expect(logs).to include(/WARN.*The key 'a' is declared more than once/) end it 'allows undefined variables (strict_variables=false)' do result = run_cli_json(%w[plan run basic::strict_variables] + config_flags) notify = get_notifies(result) expect(notify.count).to eq(1) expect(notify[0]['parameters']['message']).to eq('hello ') end it 'applies a complex type from the modulepath' do result = run_cli_json(%w[plan run basic::type] + config_flags) report = result[0]['value']['report'] warn = report['catalog']['resources'].select { |r| r['type'] == 'Warn' } expect(warn.count).to eq(1) end it 'evaluates a node definition matching the node name' do result = run_cli_json(%w[plan run basic::node_definition] + config_flags) report = result[0]['value']['report'] warn = report['catalog']['resources'].select { |r| r['type'] == 'Warn' } expect(warn.count).to eq(1) end it 'evaluates a default node definition if none matches the node name' do result = run_cli_json(%w[plan run basic::node_default] + config_flags) report = result[0]['value']['report'] warn = report['catalog']['resources'].select { |r| r['type'] == 'Warn' } expect(warn.count).to eq(1) end it 'logs messages emitted during compilation' do result = run_cli_json(%w[plan run basic::error] + config_flags) expect(result[0]['status']).to eq('success') logs = @log_output.readlines expect(logs).to include(/DEBUG.*Debugging/) expect(logs).to include(/INFO.*Meh/) expect(logs).to include(/WARN.*Warned/) expect(logs).to include(/NOTICE.*Helpful/) expect(logs).to include(/ERROR.*Fire/) expect(logs).to include(/ERROR.*Stop/) expect(logs).to include(/FATAL.*Drop/) expect(logs).to include(/FATAL.*Roll/) end it 'fails immediately on a compile error' do result = run_cli_json(%w[plan run basic::catch_error catch=false] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines) .to include(/stop the insanity/) end it 'returns a ResultSet containing failure with _catch_errors=true' do result = run_cli_json(%w[plan run basic::catch_error catch=true] + config_flags) expect(result['kind']).to eq('bolt/apply-error') expect(result['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines) .to include(/stop the insanity/) end it 'errors calling run_task' do result = run_cli_json(%w[plan run basic::disabled] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines) .to include(/Plan language function 'run_task' cannot be used from declarative manifest code/) end context 'with puppetdb misconfigured' do let(:pdb_conf) { { 'server_urls' => 'https://puppetdb.example.com', 'cacert' => '/path/to/cacert' } } let(:config) { {} } it 'calls puppetdb_query' do result = run_cli_json(%w[plan run basic::pdb_query] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines).to include(/Failed to connect to all PuppetDB server_urls/) end it 'calls puppetdb_fact' do result = run_cli_json(%w[plan run basic::pdb_fact] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines).to include(/Failed to connect to all PuppetDB server_urls/) end end context 'with hiera config stubbed' do let(:default_datadir) { { 'hiera-config' => File.join(__dir__, '../fixtures/apply/hiera.yaml').to_s } } let(:custom_datadir) { { 'hiera-config' => File.join(__dir__, '../fixtures/apply/hiera_datadir.yaml').to_s } } let(:bad_hiera_version) { { 'hiera-config' => File.join(__dir__, '../fixtures/apply/hiera_invalid.yaml').to_s } } let(:eyaml_config) { { "version" => 5, "defaults" => { "data_hash" => "yaml_data", "datadir" => File.join(__dir__, '../fixtures/apply/data').to_s }, "hierarchy" => [{ "name" => "Encrypted Data", "lookup_key" => "eyaml_lookup_key", "paths" => ["secure.eyaml"], "options" => { "pkcs7_private_key" => File.join(__dir__, '../fixtures/keys/private_key.pkcs7.pem').to_s, "pkcs7_public_key" => File.join(__dir__, '../fixtures/keys/public_key.pkcs7.pem').to_s } }] } } it 'default datadir is accessible' do with_tempfile_containing('conf', YAML.dump(default_datadir)) do |conf| result = run_cli_json(%W[plan run basic::hiera_lookup --configfile #{conf.path}] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("hello default datadir") end end it 'non-default datadir specified in hiera config is accessible' do with_tempfile_containing('conf', YAML.dump(custom_datadir)) do |conf| result = run_cli_json(%W[plan run basic::hiera_lookup --configfile #{conf.path}] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("hello custom datadir") end end it 'hiera eyaml can be decoded' do with_tempfile_containing('yaml', YAML.dump(eyaml_config)) do |yaml_data| config = { 'hiera-config' => yaml_data.path.to_s } with_tempfile_containing('conf', YAML.dump(config)) do |conf| result = run_cli_json(%W[plan run basic::hiera_lookup --configfile #{conf.path}] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("hello encrypted value") end end end it 'hiera 5 version not specified' do with_tempfile_containing('conf', YAML.dump(bad_hiera_version)) do |conf| result = run_cli_json(%W[plan run basic::hiera_lookup --configfile #{conf.path}] + config_flags) expect(result['kind']).to eq('bolt/parse-error') expect(result['msg']).to match(/Hiera v5 is required, found v3/) end end end context 'with inventoryfile stubbed' do let(:inventory) { { 'inventoryfile' => File.join(__dir__, '../fixtures/apply/inventory.yaml').to_s } } it 'vars cannot be set on the target' do with_tempfile_containing('conf', YAML.dump(inventory)) do |conf| result = run_cli_json(%W[plan run basic::xfail_set_var --configfile #{conf.path}] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') expect(result['msg']).to match(/Apply failed to compile for/) end end it 'features cannot be set on the target' do with_tempfile_containing('conf', YAML.dump(inventory)) do |conf| result = run_cli_json(%W[plan run basic::xfail_set_feature --configfile #{conf.path}] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') expect(result['msg']).to match(/Apply failed to compile for/) end end end context 'with Bolt plan datatypes' do let(:inventory) { File.join(__dir__, '../fixtures/apply/inventory.yaml') } let(:tflags) { %W[--no-host-key-check --inventoryfile #{inventory} --run-as root] } it 'serializes ResultSet objects in apply blocks' do result = run_cli_json(%w[plan run puppet_types::resultset] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("ResultSet target names: [ssh://bolt@localhost:20022]") end it 'serializes Result objects in apply blocks' do result = run_cli_json(%w[plan run puppet_types::result] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("Result value: root\n") expect(notify[1]['title']).to eq("Result target name: ssh://bolt@localhost:20022") end it 'serializes ApplyResult objects in apply blocks' do result = run_cli_json(%w[plan run puppet_types::applyresult] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("ApplyResult resource: /home/bolt/tmp") end it 'serializes Target objects as ApplyTargets in apply blocks' do result = run_cli_json(%w[plan run puppet_types::target] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("ApplyTarget protocol: ssh") end it 'serializes Error objects in apply blocks' do result = run_cli_json(%w[plan run puppet_types::error] + config_flags) notify = get_notifies(result) expect(notify[0]['title']).to eq("ApplyResult resource: The command failed with exit code 127") end context 'when calling invalid functions in apply' do it 'errors when get_targets is called' do result = run_cli_json(%w[plan run puppet_types::get_targets] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines) .to include(/The function 'get_targets' is not callable within an apply block/) end it 'errors when get_target is called' do result = run_cli_json(%w[plan run puppet_types::get_target] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines) .to include(/The function 'get_target' is not callable within an apply block/) end it 'errors when Target.new is called' do result = run_cli_json(%w[plan run puppet_types::target_new] + config_flags) expect(result['kind']).to eq('bolt/apply-failure') error = result['details']['result_set'][0]['value']['_error'] expect(error['kind']).to eq('bolt/apply-error') expect(error['msg']).to match(/Apply failed to compile for #{uri}/) expect(@log_output.readlines) .to include(/Target objects cannot be instantiated inside apply blocks/) end end end end end
# location.rb require 'json' module GoCLI # Location class class Location attr_accessor :name, :coord def initialize(opts = {}) @name = opts[:name] || '' @coord = opts[:coord] || [] end def self.load_all locs = [] return locs unless File.file?("#{Dir.pwd}/data/locations.json") file = File.read("#{Dir.pwd}/data/locations.json") data = JSON.parse(file) data.each do |l| locs << new( name: l['name'], coord: l['coord'] ) end locs end def self.find(location_name) locations = load_all coordinate = self.new locations.each do |loc| if loc.name == location_name.downcase coordinate.coord = loc.coord coordinate.name = loc.name return coordinate end end coordinate end def self.calculate_distance(origin, destination) Math.sqrt(((destination[0] - origin[0])**2 + (destination[1] - origin[1])**2).to_f) end end end
class Patient < ApplicationRecord validates :name, presence: true validates :age, presence: true, :numericality => true validates :weight, presence: true, :numericality => true validates :disease, presence: true validates :admit_date, presence: true validates :release_date, presence: true end
class Api::V1::UsersController < ApplicationController def index @users = User.all render json: @users end def show @user = User.find(params[:id]) render json: @user end def create @user = User.new(user_params) if @user.save jwt = encode_token({user_id: @user.id}) render json: {user: UserSerializer.new(@user), jwt: jwt} else puts 'bad request' end end def update @user = User.find(params[:id]) @user.update(user_params) render json: @user end def destroy @user = User.find(params[:id]) @user.destroy render json: @user end private def user_params params.permit(:username, :password, :name, :city, :role, :profile_pic, :photo) end end
extend Algebrick::Matching # => main def deliver_email(email) true end Contact = Algebrick.type do |contact| variants Null = atom, contact fields username: String, email: String end # => Contact(Null | Contact(username: String, email: String)) module Contact def username match self, Null >> 'no name', Contact >-> { self[:username] } end def email match self, Null >> 'no email', Contact >-> { self[:email] } end def deliver_personalized_email match self, Null >> true, Contact >-> { deliver_email(self.email) } end end peter = Contact['peter', 'example@dot.com'] # => Contact[username: peter, email: example@dot.com] john = Contact[username: 'peter', email: 'example@dot.com'] # => Contact[username: peter, email: example@dot.com] nobody = Null # => Null [peter, john, nobody].map &:email # => ["example@dot.com", "example@dot.com", "no email"] [peter, john, nobody].map &:deliver_personalized_email # => [true, true, true]
require 'rails_helper' describe 'Proxies: Slug' do before do @user = create(:user) login_as(@user) end it 'saves the slug and redirects to wizard step one' do visit dashboard_slug_path fill_in 'user_slug', with: 'mothers-of-invention' click_button 'Save' expect(page).to have_current_path(dashboard_proxy_wizard_step_one_path) expect(@user.reload.slug).to eq('mothers-of-invention') end end
jruby = !!() Gem::Specification.new do |s| s.name = "c_geohash" s.version = '1.1.2' s.date = "2014-11-12" s.summary = "Geohash library that wraps native C in Ruby" s.email = ["dave@popvox.com", "drew@mapzen.com"] s.homepage = "https://github.com/mapzen/geohash" s.description = "C_Geohash provides support for manipulating Geohash strings in Ruby. See http://en.wikipedia.org/wiki/Geohash. This is an actively maintained fork of the original http://rubygems.org/gems/geohash" s.has_rdoc = true s.licenses = ['MIT'] s.authors = ["David Troy", "Drew Dara-Abrams"] if ENV['JRUBY'] || RUBY_PLATFORM =~ /java/ s.files = Dir.glob('lib/**/*') s.platform = 'java' else s.files = Dir.glob('ext/*') + ['lib/geohash.rb'] s.platform = Gem::Platform::RUBY s.extensions << 'ext/extconf.rb' end s.test_files = ["test/test_geohash.rb"] s.rdoc_options = ["--main", "README.md"] s.extra_rdoc_files = ["README.md", "LICENSE.md"] s.add_development_dependency("minitest", "~> 5.4") s.add_development_dependency("rake", "~> 10.3") s.add_development_dependency("rake-compiler", "~> 0.9") end
class Photo < ActiveRecord::Base belongs_to :category def self.new_flickr(flickr_id) Photo.find_by_flickr_id(flickr_id) end end
require 'tre-ruby' class FuzzyScanner attr_accessor :regex # allow fuzziness of 2 by default def fscan!(str, fuzziness=2) str.gsub!(/\n/, " ") words = str.extend(TRE).ascan regex, TRE.fuzziness(fuzziness) words.uniq end end
module ValidationHelpers # Returns translated AR validation message # Example usage # dsc_validation_msg(:contact, :email_address, :too_long, count: 255) def dsc_validation_msg(model, attribute, validation, args = {}) key = ".#{model}.attributes.#{attribute}.#{validation}" args[:scope] = "activerecord.errors.models" I18n.t(key, args) end end
class Admin::UsersController < AdminController def index @users = User.all end def new @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to [:admin, @user] else render 'new' end end def edit @user = User.find(params[:id]) end def update @user = User.find(params[:id]) if @user.update(user_params) flash[:success] = 'You have updated profile!' redirect_to [:admin, @user] else render 'edit' end end def show @user = User.find(params[:id]) end private def user_params params.require(:user).permit(:first_name, :last_name, :middle_name, :email, :birth_date, :skype, :phone, :avatar, :admin) end end
class PokemonsController < ApplicationController def create trainer = Trainer.find(params[:trainerId]) if trainer.pokemons.length < 6 name = Faker::Name.first_name species = Faker::Games::Pokemon.name trainer.pokemons.build(nickname: name, species: species) trainer.save render json: trainer.pokemons.last else render json: { status: "error", message: 'bad request - maximum pokemon exceeded' }, status: 400 end end def destroy trainer = Trainer.find(params[:trainerId]) pokemon = Pokemon.find(params[:pokemonId]) # pokemon = Pokemon.destroy(params[:pokemonId]) trainer.pokemons.destroy(pokemon) render json: pokemon end end
# This is both a feature and a controller spec and the controller spec doesn't test the route describe "Logging out" do context 'a user is signed in' do before do login_as(create(:user)) end it 'allows logout via the header button' do visit '/' expect(page).not_to have_content('Sign in') expect(page).to have_button('Logout') click_on 'Logout' expect(current_path).to eq('/') expect(page).to have_content('Sign in') expect(page).not_to have_button('Logout') end end end
require 'spec_helper' describe User do it { should validate_presence_of :username} it { should validate_presence_of :email } it { should validate_presence_of :first_name } it { should validate_presence_of :last_name} it { should validate_presence_of :promotion } it { should validate_uniqueness_of :username } end
require 'cocoapods-core' require 'fileutils' require 'cocoapods-lazy/logger' module Pod module Lazy class Repository def initialize(repository) @repository = repository end def fetch @fetched_checksum = read_podfile_checksum() if @fetched_checksum.nil? Pod::Lazy::Logger.info "Podfile.lock not found" @is_generated_pods = true elsif @fetched_checksum != read_manifest_checksum() Pod::Lazy::Logger.info 'Checksum IS NOT EQUAL' Pod::Lazy::Logger.info 'Drop Pods directory' `rm -rf Pods` file_name = add_xcode_version @fetched_checksum @repository.fetch(name: file_name) @is_generated_pods = !Dir.exist?('Pods') else Pod::Lazy::Logger.info 'Checksum IS EQUAL' @is_generated_pods = false end end def should_store @is_generated_pods || is_modified_pods? end def store Pod::Lazy::Logger.info "Reason for store: #{store_reason || 'Not reason for store'}" @fetched_checksum = @fetched_checksum || read_podfile_checksum() file_name = add_xcode_version @fetched_checksum @repository.store(name: file_name) end private def is_modified_pods? @fetched_checksum != read_manifest_checksum() end def store_reason if @is_generated_pods "Pods is generated (not cached) so should be stored" elsif is_modified_pods? "Manifest is modified so should be stored" else nil end end def read_podfile_checksum read_checksum_from_lockfile('Podfile.lock') end def read_manifest_checksum read_checksum_from_lockfile('./Pods/Manifest.lock') end def read_checksum_from_lockfile(name) path = Pathname.new(name) return nil unless path.exist? lockfile = Lockfile.from_file(path.realpath) lockfile.internal_data['PODFILE CHECKSUM'] end def add_xcode_version(name) name + "_" + xcode_version end def xcode_version info = `xcodebuild -version` info.lines.first.sub!(" ", "_").chomp end end end end
# Using the code from hello_sophie.rb, move the greeting from the # #initialize method to an instance method named #greet that prints a greeting # when invoked. class Cat def initialize(name) @name = name end def greet puts "Hello, #{@name}!" end end kitty = Cat.new("Owen") kitty.greet
class CartsController < ApplicationController before_action :authenticate_user!, only: [:index, :new, :create, :edit, :destroy, :update] def new if Cart.exists?(user_id: current_user.id) @carts = Cart.where(user_id: current_user.id) ## whereで該当するデータ全てが返ってくる else redirect_to root_path ## 空の場合のリダイレクト先 end @user = current_user @addresses = @user.addresses end def index @carts = Cart.where(user_id: current_user.id) ## whereで該当する商品全て持ってくる @user = current_user @addresses = @user.addresses end def create #@cart = current_user.carts.build(cart_params) #user_cart = current_user.carts.where(item_id: params[:cart][:item_id].to_i).first @cart = Cart.new @cart.user_id = current_user.id @cart.amount = 1 @cart.item_id = params[:item_id].to_i @cart.item_color_id = params[:item_color_id] @cart.item_color_size_id = params[:item_color_size_id] if @cart.save redirect_to new_user_cart_path(current_user.id) else @items = Item.page(params[:page]).per(10).reverse_order render 'items/index' end end def update @carts = Cart.where(user_id: current_user.id) @carts.each_with_index do |cart, i| if cart.update(amount: params[:amount][i.to_s]) else @items = Item.page(params[:page]).per(10).reverse_order render 'items/index' end end redirect_to new_order_path end def destroy @item = Cart.find(params[:id]) @item.destroy redirect_to new_user_cart_path(current_user.id) end private def split_address(address) array = address.split { delivery_last_name: array[0], delivery_first_name: array[1], delivery_last_kana_name: array[2], delivery_first_kana_name: array[3], postal_code: array[4], prefecture: array[5], city_address: array[6], building: array[7]} # splitメソッドで区切って配列にする、デフォでスペースで区切ってくれるので今回引数はなし end def cart_params case params[:address].to_i when 0 address_data = { delivery_last_name: current_user.last_name, delivery_first_name: current_user.first_name, postal_code: current_user.postal_code, prefecture: current_user.prefecture, city_address: current_user.city_address, building: current_user.building} payment_data = {delivery_first_kana_name: current_user.first_kana_name, delivery_last_kana_name: current_user.last_kana_name, payment: params[:payment].to_i, purchase_price: 600, status: 0} when 1 address = params[:other_address] address_data = split_address(address) payment_data = { payment: params[:payment].to_i, purchase_price: current_user.cart_sum, postage: 600, status: 0} end address_data.merge(payment_data) end def order_update_params params.require(:order).permit(:delivery_last_name, :delivery_first_name, :delivery_last_kana_name, :delivery_first_kana_name, :postal_code, :city_address, :prefecture, :building) end end
require 'mysql' # Monkey patch Mysql::Result to yield hashes with symbol keys class Mysql::Result MYSQL_TYPES = { 0 => :to_d, # MYSQL_TYPE_DECIMAL 1 => :to_i, # MYSQL_TYPE_TINY 2 => :to_i, # MYSQL_TYPE_SHORT 3 => :to_i, # MYSQL_TYPE_LONG 4 => :to_f, # MYSQL_TYPE_FLOAT 5 => :to_f, # MYSQL_TYPE_DOUBLE # 6 => ??, # MYSQL_TYPE_NULL 7 => :to_time, # MYSQL_TYPE_TIMESTAMP 8 => :to_i, # MYSQL_TYPE_LONGLONG 9 => :to_i, # MYSQL_TYPE_INT24 10 => :to_date, # MYSQL_TYPE_DATE 11 => :to_time, # MYSQL_TYPE_TIME 12 => :to_time, # MYSQL_TYPE_DATETIME 13 => :to_i, # MYSQL_TYPE_YEAR 14 => :to_date, # MYSQL_TYPE_NEWDATE # 15 => :to_s # MYSQL_TYPE_VARCHAR # 16 => :to_s, # MYSQL_TYPE_BIT 246 => :to_d, # MYSQL_TYPE_NEWDECIMAL 247 => :to_i, # MYSQL_TYPE_ENUM 248 => :to_i # MYSQL_TYPE_SET # 249 => :to_s, # MYSQL_TYPE_TINY_BLOB # 250 => :to_s, # MYSQL_TYPE_MEDIUM_BLOB # 251 => :to_s, # MYSQL_TYPE_LONG_BLOB # 252 => :to_s, # MYSQL_TYPE_BLOB # 253 => :to_s, # MYSQL_TYPE_VAR_STRING # 254 => :to_s, # MYSQL_TYPE_STRING # 255 => :to_s # MYSQL_TYPE_GEOMETRY } def convert_type(v, type) v ? ((t = MYSQL_TYPES[type]) ? v.send(t) : v) : nil end def columns(with_table = nil) unless @columns @column_types = [] @columns = fetch_fields.map do |f| @column_types << f.type (with_table ? "#{f.table}.#{f.name}" : f.name).to_sym end end @columns end def each_array(with_table = nil) c = columns while row = fetch_row c.each_with_index do |f, i| if (t = MYSQL_TYPES[@column_types[i]]) && (v = row[i]) row[i] = v.send(t) end end row.keys = c yield row end end def each_hash(with_table = nil) c = columns while row = fetch_row h = {} c.each_with_index {|f, i| h[f] = convert_type(row[i], @column_types[i])} yield h end end end module Sequel module MySQL class Database < Sequel::Database set_adapter_scheme :mysql def server_version @server_version ||= pool.hold do |conn| if conn.respond_to?(:server_version) pool.hold {|c| c.server_version} else get(:version[]) =~ /(\d+)\.(\d+)\.(\d+)/ ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i end end end def serial_primary_key_options {:primary_key => true, :type => :integer, :auto_increment => true} end AUTO_INCREMENT = 'AUTO_INCREMENT'.freeze def auto_increment_sql AUTO_INCREMENT end def connect conn = Mysql.init conn.options(Mysql::OPT_LOCAL_INFILE, "client") conn.real_connect( @opts[:host] || 'localhost', @opts[:user], @opts[:password], @opts[:database], @opts[:port], @opts[:socket], Mysql::CLIENT_MULTI_RESULTS + Mysql::CLIENT_MULTI_STATEMENTS + Mysql::CLIENT_COMPRESS ) conn.query_with_result = false if encoding = @opts[:encoding] || @opts[:charset] conn.query("set character_set_connection = '#{encoding}'") conn.query("set character_set_client = '#{encoding}'") conn.query("set character_set_results = '#{encoding}'") end conn.reconnect = true conn end def disconnect @pool.disconnect {|c| c.close} end def tables @pool.hold do |conn| conn.list_tables.map {|t| t.to_sym} end end def dataset(opts = nil) MySQL::Dataset.new(self, opts) end def execute(sql, &block) @logger.info(sql) if @logger @pool.hold do |conn| conn.query(sql) block[conn] if block end end def execute_select(sql, &block) execute(sql) do |c| r = c.use_result begin block[r] ensure r.free end end end def alter_table_sql(table, op) type = type_literal(op[:type]) type << '(255)' if type == 'varchar' case op[:op] when :rename_column "ALTER TABLE #{table} CHANGE COLUMN #{literal(op[:name])} #{literal(op[:new_name])} #{type}" when :set_column_type "ALTER TABLE #{table} CHANGE COLUMN #{literal(op[:name])} #{literal(op[:name])} #{type}" when :drop_index "DROP INDEX #{default_index_name(table, op[:columns])} ON #{table}" else super(table, op) end end def column_definition_sql(column) if column[:type] == :check return constraint_definition_sql(column) end sql = "#{literal(column[:name].to_sym)} #{TYPES[column[:type]]}" column[:size] ||= 255 if column[:type] == :varchar elements = column[:size] || column[:elements] sql << "(#{literal(elements)})" if elements sql << UNSIGNED if column[:unsigned] sql << UNIQUE if column[:unique] sql << NOT_NULL if column[:null] == false sql << NULL if column[:null] == true sql << " DEFAULT #{literal(column[:default])}" if column.include?(:default) sql << PRIMARY_KEY if column[:primary_key] sql << " #{auto_increment_sql}" if column[:auto_increment] if column[:table] sql << ", FOREIGN KEY (#{literal(column[:name].to_sym)}) REFERENCES #{column[:table]}" sql << "(#{literal(column[:key])})" if column[:key] sql << " ON DELETE #{on_delete_clause(column[:on_delete])}" if column[:on_delete] end sql end def index_definition_sql(table_name, index) index_name = index[:name] || default_index_name(table_name, index[:columns]) unique = "UNIQUE " if index[:unique] case index[:type] when :full_text "CREATE FULLTEXT INDEX #{index_name} ON #{table_name} (#{literal(index[:columns])})" when :spatial "CREATE SPATIAL INDEX #{index_name} ON #{table_name} (#{literal(index[:columns])})" when nil "CREATE #{unique}INDEX #{index_name} ON #{table_name} (#{literal(index[:columns])})" else "CREATE #{unique}INDEX #{index_name} ON #{table_name} (#{literal(index[:columns])}) USING #{index[:type]}" end end def transaction @pool.hold do |conn| @transactions ||= [] if @transactions.include? Thread.current return yield(conn) end conn.query(SQL_BEGIN) begin @transactions << Thread.current result = yield(conn) conn.query(SQL_COMMIT) result rescue => e conn.query(SQL_ROLLBACK) raise e unless Error::Rollback === e ensure @transactions.delete(Thread.current) end end end # Changes the database in use by issuing a USE statement. def use(db_name) disconnect @opts[:database] = db_name if self << "USE #{db_name}" self end end class Dataset < Sequel::Dataset def quote_column_ref(c); "`#{c}`"; end TRUE = '1' FALSE = '0' # Join processing changed after MySQL v5.0.12. NATURAL # joins are SQL:2003 consistent. JOIN_TYPES = { :cross => 'INNER JOIN'.freeze, :straight => 'STRAIGHT_JOIN'.freeze, :natural_left => 'NATURAL LEFT JOIN'.freeze, :natural_right => 'NATURAL RIGHT JOIN'.freeze, :natural_left_outer => 'NATURAL LEFT OUTER JOIN'.freeze, :natural_right_outer => 'NATURAL RIGHT OUTER JOIN'.freeze, :left => 'LEFT JOIN'.freeze, :right => 'RIGHT JOIN'.freeze, :left_outer => 'LEFT OUTER JOIN'.freeze, :right_outer => 'RIGHT OUTER JOIN'.freeze, :natural_inner => 'NATURAL LEFT JOIN'.freeze, # :full_outer => 'FULL OUTER JOIN'.freeze, # # A full outer join, nor a workaround implementation of # :full_outer, is not yet possible in Sequel. See issue # #195 which probably depends on issue #113 being # resolved. :inner => 'INNER JOIN'.freeze } def literal(v) case v when LiteralString v when String "'#{v.gsub(/'|\\/, '\&\&')}'" when true TRUE when false FALSE else super end end # Returns a join clause based on the specified join type # and condition. MySQL's NATURAL join is 'semantically # equivalent to a JOIN with a USING clause that names all # columns that exist in both tables. The constraint # expression may be nil, so join expression can accept two # arguments. # # === Note # Full outer joins (:full_outer) are not implemented in # MySQL (as of v6.0), nor is there currently a work around # implementation in Sequel. Straight joins with 'ON # <condition>' are not yet implemented. # # === Example # @ds = MYSQL_DB[:nodes] # @ds.join_expr(:natural_left_outer, :nodes) # # 'NATURAL LEFT OUTER JOIN nodes' # def join_expr(type, table, expr = nil, options = {}) raise Error::InvalidJoinType, "Invalid join type: #{type}" unless join_type = JOIN_TYPES[type || :inner] server_version = @opts[:server_version] ||= @db.server_version type = :inner if type == :cross && !expr.nil? if (server_version >= 50014) && /\Anatural|cross|straight\z/.match(type.to_s) table = "( #{literal(table)} )" if table.is_a?(Array) "#{join_type} #{table}" else super end end def insert_default_values_sql "INSERT INTO #{@opts[:from]} () VALUES ()" end def match_expr(l, r) case r when Regexp r.casefold? ? \ "(#{literal(l)} REGEXP #{literal(r.source)})" : "(#{literal(l)} REGEXP BINARY #{literal(r.source)})" else super end end # MySQL expects the having clause before the order by clause. def select_sql(opts = nil) opts = opts ? @opts.merge(opts) : @opts if sql = opts[:sql] return sql end columns = opts[:select] select_columns = columns ? column_list(columns) : WILDCARD if distinct = opts[:distinct] distinct_clause = distinct.empty? ? "DISTINCT" : "DISTINCT ON (#{column_list(distinct)})" sql = "SELECT #{distinct_clause} #{select_columns}" else sql = "SELECT #{select_columns}" end if opts[:from] sql << " FROM #{source_list(opts[:from])}" end if join = opts[:join] sql << join end if where = opts[:where] sql << " WHERE #{where}" end if group = opts[:group] sql << " GROUP BY #{column_list(group)}" end if having = opts[:having] sql << " HAVING #{having}" end if order = opts[:order] sql << " ORDER BY #{column_list(order)}" end if limit = opts[:limit] sql << " LIMIT #{limit}" if offset = opts[:offset] sql << " OFFSET #{offset}" end end if union = opts[:union] sql << (opts[:union_all] ? \ " UNION ALL #{union.sql}" : " UNION #{union.sql}") elsif intersect = opts[:intersect] sql << (opts[:intersect_all] ? \ " INTERSECT ALL #{intersect.sql}" : " INTERSECT #{intersect.sql}") elsif except = opts[:except] sql << (opts[:except_all] ? \ " EXCEPT ALL #{except.sql}" : " EXCEPT #{except.sql}") end sql end alias_method :sql, :select_sql def full_text_search(cols, terms, opts = {}) mode = opts[:boolean] ? " IN BOOLEAN MODE" : "" filter("MATCH (#{literal(cols)}) AGAINST (#{literal(terms)}#{mode})") end # MySQL allows HAVING clause on ungrouped datasets. def having(*cond, &block) @opts[:having] = {} filter(*cond, &block) end # MySQL supports ORDER and LIMIT clauses in UPDATE statements. def update_sql(values, opts = nil, &block) sql = super opts = opts ? @opts.merge(opts) : @opts if order = opts[:order] sql << " ORDER BY #{column_list(order)}" end if limit = opts[:limit] sql << " LIMIT #{limit}" end sql end def replace_sql(*values) if values.empty? "REPLACE INTO #{@opts[:from]} DEFAULT VALUES" else values = values[0] if values.size == 1 # if hash or array with keys we need to transform the values if @transform && (values.is_a?(Hash) || (values.is_a?(Array) && values.keys)) values = transform_save(values) end case values when Array if values.empty? "REPLACE INTO #{@opts[:from]} DEFAULT VALUES" elsif values.keys fl = values.keys.map {|f| literal(f.is_a?(String) ? f.to_sym : f)} vl = values.values.map {|v| literal(v)} "REPLACE INTO #{@opts[:from]} (#{fl.join(COMMA_SEPARATOR)}) VALUES (#{vl.join(COMMA_SEPARATOR)})" else "REPLACE INTO #{@opts[:from]} VALUES (#{literal(values)})" end when Hash if values.empty? "REPLACE INTO #{@opts[:from]} DEFAULT VALUES" else fl, vl = [], [] values.each {|k, v| fl << literal(k.is_a?(String) ? k.to_sym : k); vl << literal(v)} "REPLACE INTO #{@opts[:from]} (#{fl.join(COMMA_SEPARATOR)}) VALUES (#{vl.join(COMMA_SEPARATOR)})" end when Dataset "REPLACE INTO #{@opts[:from]} #{literal(values)}" else if values.respond_to?(:values) replace_sql(values.values) else "REPLACE INTO #{@opts[:from]} VALUES (#{literal(values)})" end end end end # MySQL supports ORDER and LIMIT clauses in DELETE statements. def delete_sql(opts = nil) sql = super opts = opts ? @opts.merge(opts) : @opts if order = opts[:order] sql << " ORDER BY #{column_list(order)}" end if limit = opts[:limit] sql << " LIMIT #{limit}" end sql end def insert(*values) @db.execute(insert_sql(*values)) {|c| c.insert_id} end def update(*args, &block) @db.execute(update_sql(*args, &block)) {|c| c.affected_rows} end def replace(*args) @db.execute(replace_sql(*args)) {|c| c.insert_id} end def delete(opts = nil) @db.execute(delete_sql(opts)) {|c| c.affected_rows} end def fetch_rows(sql) @db.execute_select(sql) do |r| @columns = r.columns r.each_hash {|row| yield row} end self end def multi_insert_sql(columns, values) columns = literal(columns) values = values.map {|r| "(#{literal(r)})"}.join(COMMA_SEPARATOR) ["INSERT INTO #{@opts[:from]} (#{columns}) VALUES #{values}"] end end end end
desc "Anchore Security Docker Vulnerability Scan" namespace :anchore do desc "Deploy a new ebrelayer to an existing cluster" task :scan, [:image, :image_tag, :app_name] do |t, args| cluster_automation = %Q{ set +x curl -s https://ci-tools.anchore.io/inline_scan-latest | bash -s -- -f -r -d cmd/#{args[:app_name]}/Dockerfile -p "#{args[:image]}:#{args[:image_tag]}" } system(cluster_automation) or exit 1 end task :scan_by_path, [:image, :image_tag, :path] do |t, args| cluster_automation = %Q{ set +x curl -s https://ci-tools.anchore.io/inline_scan-latest | bash -s -- -t 800 -d #{args[:path]}/Dockerfile -p "#{args[:image]}:#{args[:image_tag]}" #curl -s https://ci-tools.anchore.io/inline_scan-latest | bash -s -- -f -t 800 -d #{args[:path]}/Dockerfile -p "#{args[:image]}:#{args[:image_tag]}" } system(cluster_automation) or exit 1 end end
class PhotosController < ApplicationController before_filter :authenticate_user!, only: [:new, :create, :edit] def index @photos = Photo.all end def show @photo = Photo.find(params[:id]) end def new @photo = Photo.new end def create @photo = Photo.new(photo_params) if @photo.save redirect_to @photo flash[:notice] = "#{@photo.name} uploaded successfully" else render :new flash[:error] = "#{@photo.errors}" end end def edit @photo = Photo.find(params[:id]) end def update @photo = Photo.find(params[:id]) if @photo.update_attributes(photo_params) flash[:notice] = "#{@photo.name} successfully updated" redirect_to @photo else render :edit end end def destroy photo = Photo.find(params[:id]) name = photo.name photo.destroy redirect_to photos_path flash[:notice] = "#{name} deleted" end private def photo_params params.require(:photo).permit(:name, :description, :pic, :front_page) end end
# frozen_string_literal: true require_relative 'events' require_relative 'organization' # Represents overall organization information for JSON API output class OrganizationEventsRepresenter < EventsRepresenter include Roar::JSON property :organization, extend: OrganizationRepresenter, class: Organization end
# frozen_string_literal: true class User module Tokens def tokens unless current_user.any_current_tokens? redirect_to(profile_path, alert: 'You do not have any current API tokens.') end @api_tokens = current_user.api_tokens.current @persistent_api_tokens = current_user.persistent_api_tokens.current end def revoke_token klass = token_params[:persistent].present? ? PersistentApiToken : ApiToken klass.find(token_params[:id]).expire! redirect_to(profile_tokens_path, success: 'Token has been revoked.') end private def token_params params.permit(:id, :persistent) end end end
require_relative "version" module BootswatchRails module ActionViewExtensions OFFLINE = (Rails.env.development? or Rails.env.test?) def bootswatch_link_tag(theme = nil, options = {}) theme ||= BootswatchRails::THEMES[BootswatchRails::DEFAULT].to_s return stylesheet_link_tag(theme) if !options.delete(:force) and OFFLINE bootswatch_url = "//maxcdn.bootstrapcdn.com/bootswatch/#{BootswatchRails::BOOTSWATCH}/#{theme}/bootstrap.min.css" fontawesome_url = "//maxcdn.bootstrapcdn.com/font-awesome/#{BootswatchRails::FONT_AWESOME}/css/font-awesome.min.css" stylesheet_link_tag(bootswatch_url) + "\n " + stylesheet_link_tag(fontawesome_url) end def dataTables_link_tag(options = {}) return stylesheet_link_tag('jquery.dataTables') if !options.delete(:force) and OFFLINE dataTables_url = "//cdn.datatables.net/#{BootswatchRails::DATATABLES}/css/jquery.dataTables.css" stylesheet_link_tag(dataTables_url) end def dataTables_responsive_link_tag(options = {}) return stylesheet_link_tag('responsive.dataTables') if !options.delete(:force) and OFFLINE responsive_url = "//cdn.datatables.net/responsive/#{BootswatchRails::RESPONSIVE}/css/responsive.dataTables.css" stylesheet_link_tag(responsive_url) end def bootstrap_include_tag(options = {}) return javascript_include_tag(:bootstrap) if !options.delete(:force) and OFFLINE bootstrap_url = "//maxcdn.bootstrapcdn.com/bootstrap/#{BootswatchRails::BOOTSTRAP}/js/bootstrap.min.js" [ javascript_include_tag(bootstrap_url, options), javascript_tag("window.jQuery || document.write(unescape('#{javascript_include_tag(:bootstrap).gsub('<','%3C')}'))") ].join("\n").html_safe end def dataTables_include_tag(options = {}) return javascript_include_tag('jquery.dataTables') if !options.delete(:force) and OFFLINE dataTables_url = "//cdn.datatables.net/#{BootswatchRails::DATATABLES}/js/jquery.dataTables.js" [ javascript_include_tag(dataTables_url, options), javascript_tag("window.jQuery || document.write(unescape('#{javascript_include_tag('jquery.dataTables').gsub('<','%3C')}'))") ].join("\n").html_safe end def dataTables_responsive_include_tag(options = {}) return javascript_include_tag('dataTables.responsive') if !options.delete(:force) and OFFLINE responsive_url = "//cdn.datatables.net/responsive/#{BootswatchRails::RESPONSIVE}/js/dataTables.responsive.js" [ javascript_include_tag(responsive_url, options), javascript_tag("window.jQuery || document.write(unescape('#{javascript_include_tag('dataTables.responsive').gsub('<','%3C')}'))") ].join("\n").html_safe end end class Engine < Rails::Engine initializer "BootswatchRails" do |app| ActiveSupport.on_load(:action_view) do include BootswatchRails::ActionViewExtensions end app.config.assets.precompile += %w(jquery.dataTables.css responsive.dataTables.css cerulean.css cosmo.css custom.css cyborg.css darkly.css flatly.css journal.css lumen.css paper.css readable.css sandstone.css simplex.css slate.css solar.css spacelab.css superhero.css united.css yeti.css) app.config.assets.paths << File.expand_path('../../../vendor/assets/fonts', __FILE__) end end end
# TEM cryptographic key manipulation using the APDU API. # # Author:: Victor Costan # Copyright:: Copyright (C) 2007 Massachusetts Institute of Technology # License:: MIT # :nodoc: namespace module Tem::Apdus module Keys def devchip_generate_key_pair(symmetric_key = false) response = @transport.iso_apdu! :ins => 0x40, :p1 => (symmetric_key ? 0x80 : 0x00) return { :privkey_id => read_tem_byte(response, 0), :pubkey_id => read_tem_byte(response, 1) } end # NOTE: this is the only method that is not devchip-only. It needs to be in # the production driver to prevent from DOSing the TEM by filling its # key store. def release_key(key_id) @transport.iso_apdu! :ins => 0x28, :p1 => key_id return true end def devchip_save_key(key_id) response = @transport.iso_apdu! :ins => 0x42, :p1 => key_id buffer_id = read_tem_byte response, 0 buffer_length = read_tem_short response, 1 key_buffer = read_buffer buffer_id release_buffer buffer_id read_tem_key key_buffer[0, buffer_length], 0 end def devchip_encrypt_decrypt(data, key_id, opcode) buffer_id = post_buffer data begin response = @transport.iso_apdu! :ins => opcode, :p1 => key_id, :p2 => buffer_id ensure release_buffer buffer_id end buffer_id = read_tem_byte response, 0 buffer_length = read_tem_short response, 1 data_buffer = read_buffer buffer_id release_buffer buffer_id return data_buffer[0, buffer_length] end def devchip_encrypt(data, key_id) devchip_encrypt_decrypt data, key_id, 0x43 end def devchip_decrypt(data, key_id) devchip_encrypt_decrypt data, key_id, 0x44 end def stat_keys response = @transport.iso_apdu! :ins => 0x27, :p1 => 0x01 key_types = { 0x99 => :symmetric, 0x55 => :private, 0xAA => :public } stat = {:keys => {}} offset = 0 while offset < response.length do stat[:keys][read_tem_ubyte(response, offset)] = { :type => key_types[read_tem_ubyte(response, offset + 1)], :bits => read_tem_ushort(response, offset + 2) } offset += 4 end return stat end end end # namespace Tem::Apdus
class ChangePaperclipColumns < ActiveRecord::Migration def change rename_column :attachments, :image_file_name, :attachment_file_name rename_column :attachments, :image_content_type, :attachment_content_type rename_column :attachments, :image_file_size, :attachment_file_size rename_column :attachments, :image_updated_at, :attachment_updated_at end end
require 'minitest/autorun' require 'minitest/pride' require './lib/grid' class GridTest < Minitest::Test def test_it_exists g = Grid.new assert g end def test_it_starts_with_4x4_grid_by_default g = Grid.new assert_equal [[' ']*4]*4, g.grid assert_equal 4, g.size end def test_it_can_start_with_8x8_grid g = Grid.new(8) assert_equal [[' ']*8]*8, g.grid assert_equal 8, g.size end def test_it_can_assign_and_lookup_values g = Grid.new assert_equal ' ', g.lookup("A1") g.assign("A1", 2) assert_equal 2, g.lookup("A1") assert_equal ' ', g.lookup("B1") end # def test_it_can_render_grid # skip # b = Battleship::Board.new # b.render_grid # end # # def test_it_can_render_8x8_grid # skip # Battleship::Board.new(8).render_grid # end end
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html post 'auth/token', to: 'auth#token' resources :notes, only: [:index, :create] match '*path', via: [:options], to: lambda {|_| [204, {'Content-Type' => 'text/plain'}, []]} end
# # Author:: Matt Eldridge (<matt.eldridge@us.ibm.com>) # © Copyright IBM Corporation 2014. # # LICENSE: MIT (http://opensource.org/licenses/MIT) # Shindo.tests("Fog::Compute[:softlayer] | server requests", ["softlayer"]) do tests('success') do @sl_connection = Fog::Compute[:softlayer] @bmc = { :operatingSystemReferenceCode => 'UBUNTU_LATEST', :processorCoreAmount => 2, :memoryCapacity => 2, :hourlyBillingFlag => true, :domain => 'example.com', :hostname => 'test', :datacenter => { :name => 'wdc01' } } tests("#create_bare_metal_server('#{@bmc}')") do response = @sl_connection.create_bare_metal_server(@bmc) @server_id = response.body['id'] data_matches_schema(Softlayer::Compute::Formats::BareMetal::SERVER, {:allow_extra_keys => true}) { response.body } data_matches_schema(201) { response.status } end tests("#get_bare_metal_servers()") do @sl_connection.get_bare_metal_servers.body.each do |bms| data_matches_schema(Softlayer::Compute::Formats::BareMetal::SERVER) { bms } end end tests("#delete_bare_metal_server('#{@server_id})'") do response = @sl_connection.delete_bare_metal_server(@server_id) data_matches_schema(true) {response.body} data_matches_schema(200) {response.status} end end tests('failure') do bmc = @bmc.dup; bmc.delete(:hostname) tests("#create_bare_metal_server('#{bmc}')") do response = @sl_connection.create_bare_metal_server(bmc) data_matches_schema('SoftLayer_Exception_MissingCreationProperty'){ response.body['code'] } data_matches_schema(500){ response.status } end tests("#create_bare_metal_server(#{[@bmc]}").raises(ArgumentError) do @sl_connection.create_bare_metal_server([@bmc]) end tests("#delete_bare_metal_server('99999999999999')'") do response = @sl_connection.delete_bare_metal_server(99999999999999) data_matches_schema(String) {response.body} data_matches_schema(500) {response.status} end end end
# frozen_string_literal: true require "spec_helper" RSpec.describe Tikkie::Api::V1::Requests::Users do subject { Tikkie::Api::V1::Requests::Users.new(request) } let(:config) { Tikkie::Api::V1::Configuration.new("12345", "spec/fixtures/private_rsa.pem") } let(:request) { Tikkie::Api::V1::Request.new(config) } before do # Stub authentication request token = File.read("spec/fixtures/responses/v1/token.json") stub_request(:post, "https://api.abnamro.com/v1/oauth/token").to_return(status: 200, body: token) end describe '#list' do it 'returns a list of users' do data = File.read("spec/fixtures/responses/v1/users/list.json") stub_request(:get, "https://api.abnamro.com/v1/tikkie/platforms/12345/users").to_return(status: 200, body: data) users = subject.list("12345") expect(users).to be_a(Tikkie::Api::V1::Responses::Users) expect(users.error?).to be false expect(users.count).to eq(1) user = users.first expect(user).to be_a(Tikkie::Api::V1::Responses::User) end end describe '#create' do it 'creates a new user' do data = File.read("spec/fixtures/responses/v1/users/create.json") stub_request(:post, "https://api.abnamro.com/v1/tikkie/platforms/12345/users").to_return(status: 201, body: data) user = subject.create("12345", name: "NewUser", phone_number: "0612345678", iban: "NL02ABNA0123456789", bank_account_label: "Personal account") expect(user).to be_a(Tikkie::Api::V1::Responses::User) expect(user.error?).to be false end end describe 'error handling' do it 'handles 404 errors successfully' do data = File.read("spec/fixtures/responses/v1/users/error.json") stub_request(:get, "https://api.abnamro.com/v1/tikkie/platforms/12345/users").to_return(status: 404, body: data) users = subject.list("12345") expect(users).to be_a(Tikkie::Api::V1::Responses::Users) expect(users.error?).to be true expect(users.errors).not_to be_empty expect(users.response_code).to eq(404) end it 'handles invalid json' do data = File.read("spec/fixtures/responses/v1/users/invalid.json") stub_request(:get, "https://api.abnamro.com/v1/tikkie/platforms/12345/users").to_return(status: 200, body: data) users = subject.list("12345") expect(users).to be_a(Tikkie::Api::V1::Responses::Users) expect(users.error?).to be true expect(users.errors).to be_empty expect(users.response_code).to eq(200) end end end
class AddOtherToEvents < ActiveRecord::Migration def change add_column :events, :other_games, :boolean add_column :events, :other_types, :boolean end end
class QuestionVotes < ActiveRecord::Migration def change create_table :question_votes do |qv| qv.integer :question_id qv.integer :user_id qv.integer :vote end end end
require 'sinatra/base' require 'sinatra/reloader' require 'sinatra/flash' require 'haml' require 'json' require_relative 'database' require_relative 'models/user' require_relative 'models/site' require_relative 'models/validation_error' require_relative 'models/event' require_relative 'models/analytic' require_relative 'mappers/user_mapper' require_relative 'mappers/site_mapper' require_relative 'mappers/event_mapper' $db = Database.new class App < Sinatra::Base SECONDS_IN_DAY = 86400 enable :sessions register Sinatra::Flash configure :development do register Sinatra::Reloader also_reload 'database.rb' also_reload 'mappers/user_mapper.rb' also_reload 'mappers/site_mapper.rb' also_reload 'mappers/event_mapper.rb' also_reload 'models/user.rb' also_reload 'models/site.rb' also_reload 'models/validation_error.rb' also_reload 'models/analytic.rb' end before '/site/new' do unless current_user flash[:fatal] = "Not authorized. Please login first." redirect to("/") end end get '/' do $db.increment_page_count @page_count = $db.get_page_count if current_user @sites = SiteMapper.new($db).get_sites_for_user(current_user) end haml :root, :layout => :layout end get '/users/sign-up' do haml :"users/sign-up", :layout => :layout, :locals => { :email => "" } end post '/users/sign-up' do begin user = User.new(params[:email], params[:password], params[:passwordConfirmation]) UserMapper.new($db).persist(user) flash[:info] = "Successfully signed up!" redirect to("/users/sign-in") rescue ValidationError => e flash.now[:fatal] = e.message return haml :"/users/sign-up", :layout => :layout, :locals => { :email => params[:email] } end end get '/users/sign-in' do haml :"users/sign-in", :layout => :layout end post '/users/sign-in' do if UserMapper.new($db).valid_signin_details?(params[:email], params[:password]) session[:current_user_email] = params[:email] flash[:info] = "Successfully signed in." redirect to("/") else flash.now[:error] = "Email and/or password not valid. Please try again." haml :"users/sign-in", :layout => :layout end end post '/users/sign-out' do if session[:current_user_email] session[:current_user_email] = params[:email] flash[:info] = "Successfully signed out." redirect to("/") else flash.now[:info] = "Not Signed In" end end get '/site/new' do haml :"site/new", :layout => :layout end post '/site/new' do site = Site.new(current_user, params[:url]) begin site.validate rescue ValidationError => e flash[:fatal] = e.message redirect to("/site/new") return end if SiteMapper.new($db).persist(site) flash[:info] = "Successfully added site." redirect to("/") else flash.now[:fatal] = "Site creation failed. Please try again." haml :"/site/new", :layout => :layout end end post '/events' do if !SiteMapper.new($db).find_by_code(params[:code]) status 404 else event = Event.new(params[:code], params[:name], params[:property1], params[:property2]) EventMapper.new($db).persist(event) end "" response.headers['Access-Control-Allow-Origin'] = '*' end get '/events/:code' do @site = SiteMapper.new($db).find_by_code(params[:code]) @events = EventMapper.new($db).find_events_for_code(@site.code) @date1 = Date.today-7 @date2 = Date.today @chartData = Analytic.new(@events).group_by_name haml :"/events/show", :layout => :layout end get '/events/:code/search' do @site = SiteMapper.new($db).find_by_code(params[:code]) @date1 = parse_date(params[:date1]) @date2 = parse_date(params[:date2]) @events = EventMapper.new($db).find_events_within_dates(@date1, @date2 + SECONDS_IN_DAY) @chartData = Analytic.new(@events).group_by_name haml :"/events/show", :layout => :layout end protected def current_user UserMapper.new($db).find_by_email(session[:current_user_email]) end def parse_date(date) Date.parse(date).to_time end end
require File.dirname(__FILE__) + '/../spec_helper' describe MessagesController do fixtures :all render_views describe "as guest" do it "create action should redirect to signin url" do get :create response.should redirect_to(signin_url) end end describe "as user" do before(:each) do @user = Factory(:user) @controller.stubs(:current_user).returns(@user) end it "create action should render js template and send email if user requests" do game = Factory(:game, :black_player => @user) game.opponent(@user).update_attribute(:email_on_message, true) Message.any_instance.stubs(:valid?).returns(true) post :create, :format => "js", :message => {:game_id => game.id} response.should render_template("create") assigns(:message).user == @user assigns(:message).game == game Notifications.deliveries.size.should == 1 Notifications.deliveries.first.subject.should == "[Go vs Go] Chat from #{@user.username}" end it "should not send message email when user doesn't want it" do game = Factory(:game, :black_player => @user) game.opponent(@user).update_attribute(:email_on_message, false) Message.any_instance.stubs(:valid?).returns(true) post :create, :format => "js", :message => {:game_id => game.id} response.should be_success Notifications.deliveries.size.should == 0 end it "should not send message email when user is online" do game = Factory(:game, :black_player => @user) game.opponent(@user).update_attribute(:email_on_message, true) game.opponent(@user).update_attribute(:last_request_at, Time.now) Message.any_instance.stubs(:valid?).returns(true) post :create, :format => "js", :message => {:game_id => game.id} response.should be_success Notifications.deliveries.size.should == 0 end end end
require 'rails_helper' RSpec.describe Beer, type: :model do it "is saved with a proper name, style and brewery" do beer = FactoryBot.create :beer expect(beer).to be_valid expect(Beer.count).to eq(1) end describe "that is otherwise valid" do let(:brewery) { FactoryBot.create :brewery } let(:style) { FactoryBot.create :style } it "is not saved without a brewery" do beer = Beer.create name: "Karhu", style: style expect(beer).to_not be_valid expect(Beer.count).to eq(0) end it "is not saved without a name" do beer = Beer.create brewery: brewery, style: style expect(beer).to_not be_valid expect(Beer.count).to eq(0) end it "is not saved without a style" do beer = Beer.create name: "Karhu", brewery: brewery expect(beer).to_not be_valid expect(Beer.count).to eq(0) end end end
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'mobmanager/version' Gem::Specification.new do |spec| spec.name = "mobmanager" spec.version = Mobmanager::VERSION spec.authors = ['Milton Davalos'] spec.email = ['mdavalos@mobiquityinc.com'] spec.summary = %q{Provides methods to manage Appium server} spec.description = %q{Provides methods to start/end Appium server and management of apps in Android and iOS} spec.homepage = 'https://github.com/m-davalos/mobmanager' spec.license = 'Mobiquity, Inc.' spec.files = `git ls-files`.split("\n") spec.require_paths = ["lib"] spec.add_dependency 'require_all' end
class Dispensacao < ActiveRecord::Base belongs_to :dispensavel, :polymorphic => true belongs_to :usuario has_many :agendamentos_sms attr_accessor :data_formatada validates :medicamento, :presence => true, :numericality => {:only_integer => true} validates :posologia, :presence => true validates :quantidade, :presence => true validates :data, :presence => true def data_formatada if self.data self.data.strftime("%d/%m/%Y") else nil end end def data_formatada=(data) self.data = data end end
class AddEventIndexToGame < ActiveRecord::Migration def change add_column :games, :event_index, :integer end end
require 'spec_helper' describe UsersHelper do describe "gravatar_for" do before(:each) do @user.stub_chain(:email).and_return("benbruneau@gmail.com") @user.stub_chain(:name).and_return("Ben") end it "builds an image tag with a gravatar link in it" do expect(helper.gravatar_for(@user)).to have_selector("img[src='https://secure.gravatar.com/avatar/9e734ca6f560cf168a71d7a9e0e1caa7?s=80']") expect(helper.gravatar_for(@user)).to have_selector("img[alt='Ben']") end it "accepts different sizes" do @size = 80 expect(helper.gravatar_for(@user, @size)).to have_selector("img[src='https://secure.gravatar.com/avatar/9e734ca6f560cf168a71d7a9e0e1caa7?s=#{@size}']") end end end
class AddColumnUser < ActiveRecord::Migration[5.1] def change add_column :users, :image_binary, :binary add_column :users, :image_type, :string end end
def sequence(num) array = [] 1.upto(num) { |idx| array << idx } array end puts sequence(5) == [1, 2, 3, 4, 5] puts sequence(3) == [1, 2, 3] puts sequence(1) == [1]