text
stringlengths
10
2.61M
# Schema # t.integer "user_id" # t.integer "product_id" class Wishlist < ActiveRecord::Base # Associated models belongs_to :user belongs_to :product # Accessible attributes attr_accessible :user_id, :product_id # Associated validations validates :user_id, :presence => true # validates :product_id, :presence => true, :uniqueness => {:scope => :user_id, :message => "A product cannot be added more than once"} def self.search(search="") joins(:products,:users).where("products.name LIKE '%#{search}%' OR users.first_name LIKE '%#{search}%' OR users.last_name LIKE '%#{search}%'") end end
class WrongNumberOfPlayersError < StandardError ; end class NoSuchStrategyError < StandardError ; end def rps_game_winner(game) raise WrongNumberOfPlayersError unless game.length == 2 # raise error if game strategy different from P,R or S raise NoSuchStrategyError unless game.all? {|g| g.last =~ /[PSR]/i} game_hash_map = {"R"=>"S","P"=>"R","S"=>"P"} strategy1=game[0].last.upcase strategy2=game[1].last.upcase puts "Strategy 1"+strategy1 puts "Strategy 2"+strategy2 if game_hash_map[strategy2] == strategy1 game[1] else game[0] end end def rps_tournament_winner(tournament) if tournament[0][0].is_a? String return rps_game_winner(tournament) else tA=rps_tournament_winner(tournament[0]) tB=rps_tournament_winner(tournament[1]) rps_game_winner([tA,tB]) end end
class Bill < ActiveRecord::Base has_many :movements, :dependent => :destroy has_many :menu_day, :dependent => :destroy accepts_nested_attributes_for :menu_day attr_accessor :periodo_mask before_save :check_limites belongs_to :school belongs_to :user validates :school_id, presence: true validates :tipo, presence: true validates :periodo, presence: true, uniqueness: { scope: [:school_id, :tipo], message: "Ya se ha facturado este período para esta Escuela" } validates :limite_grp_1, presence: true validates :valor_1, presence: true, :numericality => true validates :valor_2, presence: true, :numericality => true, if: "limite_grp_2 != nil" validates :valor_3, presence: true, :numericality => true, if: "limite_grp_3 != nil" validates :limite_grp_2, presence: true, if: "limite_grp_1 != nil && limite_grp_1 < " + Child::GRADOS['7mo Grado'].to_s validates :limite_grp_3, presence: true, if: "limite_grp_2 != nil && limite_grp_2 < " + Child::GRADOS['7mo Grado'].to_s TIPOS_FACTURACION = { 'Mensual' => 1, 'Diaria' => 2 } def humanized_tipo_facturacion TIPOS_FACTURACION.invert[self.tipo] end def humanized_limite_grp_1 Child::GRADOS.invert[self.limite_grp_1] end def humanized_limite_grp_2 Child::GRADOS.invert[self.limite_grp_2] end def humanized_limite_grp_3 Child::GRADOS.invert[self.limite_grp_3] end private def check_limites # Esto no impide que se grabe, sólo muestra los mensajes de error errors.add(:limite_grp_2, "El valor debe ser mayor al Límite de Grupo 1") if limite_grp_1.present? && limite_grp_2.present? && limite_grp_2 <= limite_grp_1 errors.add(:limite_grp_3, "El valor debe ser mayor al Límite de Grupo 2") if limite_grp_2.present? && limite_grp_3.present? && limite_grp_3 <= limite_grp_2 end end
require 'util/miq-xml' require 'metadata/VmConfig/VmConfig' require 'VolumeManager/MiqNativeVolumeManager' require 'fs/MiqMountManager' require 'awesome_spawn' module MiqNativeMountManager def self.mountVolumes lshwXml = AwesomeSpawn.run!("lshw", :params => ["-xml"], :combined_output => true).output nodeHash = Hash.new { |h, k| h[k] = [] } doc = MiqXml.load(lshwXml) doc.find_match("//node").each { |n| nodeHash[n.attributes["id"].split(':', 2)[0]] << n } hardware = "" nodeHash["disk"].each do |d| diskid = d.find_first('businfo').get_text.to_s next unless diskid sn = d.find_first('size') # If there's no size node, assume it's a removable drive. next unless sn busType, busAddr = diskid.split('@', 2) if busType == "scsi" f1, f2 = busAddr.split(':', 2) f2 = f2.split('.')[1] busAddr = "#{f1}:#{f2}" else busAddr['.'] = ':' end diskid = busType + busAddr filename = d.find_first('logicalname').get_text.to_s hardware += "#{diskid}.present = \"TRUE\"\n" hardware += "#{diskid}.filename = \"#{filename}\"\n" end cfg = VmConfig.new(hardware) volMgr = MiqNativeVolumeManager.new(cfg) (MiqMountManager.mountVolumes(volMgr, cfg)) end end # module MiqNativeMountManager if __FILE__ == $0 require 'logger' $log = Logger.new(STDERR) $log.level = Logger::DEBUG puts "Log debug?: #{$log.debug?}" rootTrees = MiqNativeMountManager.mountVolumes if rootTrees.nil? || rootTrees.empty? puts "No root filesystems detected" exit end $miqOut = $stdout rootTrees.each do |r| r.toXml(nil) end rootTree = rootTrees[0] if rootTree.guestOS == "Linux" puts puts "Files in /:" rootTree.dirForeach("/") { |f| puts "\t#{f}" } puts puts "All files in /test_mount:" rootTree.findEach("/test_mount") { |f| puts "\t#{f}" } elsif rootTree.guestOS == "Windows" puts puts "Files in C:/" rootTree.dirForeach("C:/") { |f| puts "\t#{f}" } ["E:/", "F:/"].each do |drive| puts puts "All files in #{drive}" rootTree.findEach(drive) { |f| puts "\t#{f}" } end else puts "Unknown guest OS: #{rootTree.guestOS}" end end
class Calculator attr_accessor :num1, :num2 def initialize(num1, num2) @num1 = num1 @num2 = num2 end def sum @num1 + @num2 end def difference @num1 - @num2 end def quotient @num1.to_f/@num2.to_f end def product @num1 * @num2 end end
# Givens Given(/^Active bill$/) do create :active_bill visit '/bills/1' end Given(/^Non Active bill$/) do create :non_active_bill visit '/bills/1' end Given(/^User is on Legislator page$/) do create :legislator visit '/legislators/1' end # Whens When(/^User attempts to tag a bill$/) do click_button 'Tag Bill' end When(/^User attempts to tag a legislator$/) do click_button 'Tag Legislator' end # Thens Then(/^User should not see a tag button with "(.*?)"$/) do |tag_text| expect(page).to_not have_content(tag_text) end Then(/^Tag button should read "(.*?)"$/) do |tag_text| expect(page).to have_content(tag_text) end
class AddDateAndTimeToReminders < ActiveRecord::Migration[5.2] def change add_column :reminders, :date, :string add_column :reminders, :time, :string end end
Time.class_eval do # Weekend cutoff is 5pm Friday to 5pm Sunday. def weekend? wday == 6 || wday == 0 && hour < 17 || wday == 5 && hour >= 17 end def weekday? ! weekend? end end
require 'couchrest_model' class Dc < CouchRest::Model::Base use_database "dashboard" property :district_code, String property :registered, Integer property :approved, Integer property :date_created, String timestamps! design do view :by__id view :by_district_code view :by_registered view :by_approved view :by_district_code_and_registered_and_approved filter :dashboard_sync, "function(doc,req) {return req.query.district_code == doc.district_code}" end end
require 'bundler' Bundler::GemHelper.install_tasks require 'rake/clean' require 'rake/testtask' task :default => [:test] task :test do Rake::TestTask.new do |t| t.libs << "test" t.pattern = 'test/*_test.rb' t.verbose = true end end desc 'Measures test coverage' task :coverage do rm_f "coverage" rm_f "coverage.data" system "rcov -x /Users -Ilib:test test/*_test.rb" system "open coverage/index.html" if PLATFORM['darwin'] end
class Vacation < ApplicationRecord belongs_to :traveler belongs_to :country end
class ManageIQ::Providers::Amazon::Inventory::Collector::StorageManager::S3 < ManageIQ::Providers::Amazon::Inventory::Collector def cloud_object_store_containers hash_collection.new(aws_s3.client.list_buckets.flat_map(&:buckets)) end def cloud_object_store_objects(options = {}) options[:token] ||= nil # S3 bucket accessible only for API client with same region regional_client = aws_s3_regional(options[:region]).client response = regional_client.list_objects_v2( :bucket => options[:bucket], :continuation_token => options[:token] ) token = response.next_continuation_token if response.is_truncated return hash_collection.new(response.contents), token rescue => e log_header = "MIQ(#{self.class.name}.#{__method__}) Collecting data for EMS name: [#{manager.name}] id: [#{manager.id}]" $aws_log.warn("#{log_header}: Unable to collect S3 objects in a bucket #{options[:bucket]}, Message: #{e.message}") $aws_log.warn(e.backtrace.join("\n")) return [], nil end private def aws_s3_regional(region) if !region || region == manager.provider_region aws_s3 else @regional_resources ||= {} @regional_resources[region] ||= manager.connect(:service => :S3, :region => region) end end end
source 'https://rubygems.org' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '4.0.2' gem 'pg', '0.17.1' # Devise gem 'devise', '3.2.1' group :assets do gem 'sass-rails', '4.0.1' gem 'coffee-rails', '4.0.1' gem 'uglifier', '1.0.4' end # Compass for CSS gem 'compass-rails', '~> 1.1.3' # Icons FontAwesome gem 'font-awesome-rails', '~> 4.0.3.1' # Bootsrap gem 'bootstrap-sass', '3.0.3.0' # jQuery gem 'jquery-rails', '3.1.0' gem 'jquery-ui-rails', '4.1.1' # AngularJS gem 'angularjs-rails', '1.2.14' # Slim gem 'slim', :git => 'git://github.com/brennancheung/slim.git', :branch => 'angularjs_support' gem 'slim-rails', '2.1.0' # TurboLinks gem 'turbolinks', '2.2.1' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '1.5.3' gem 'execjs', '2.0.2' gem 'therubyracer', '~> 0.11.0beta5', :platform => :ruby gem 'protected_attributes', '1.0.5' group :development do gem 'meta_request' end
require 'pry' class Student attr_accessor :id, :name, :grade def self.new_from_db(row) new_student = self.new # self.new is the same as running Song.new new_student.id = row[0] new_student.name = row[1] new_student.grade = row[2] new_student end def self.all sql = <<-SQL SELECT * FROM students SQL all = DB[:conn].execute(sql) all.collect do |array| Student.new.tap do |s| s.id = array[0] s.name = array[1] s.grade = array[2] end end end def self.count_all_students_in_grade_9 sql = <<-SQL SELECT * FROM students WHERE grade = 9 SQL grade_9_students = DB[:conn].execute(sql) grade_9_students.collect do |array| Student.new.tap do |s| s.id = array[0] s.name = array[1] s.grade = array[2] end end end def self.students_below_12th_grade sql = <<-SQL SELECT * FROM students WHERE grade = 12 SQL grade_12_students = DB[:conn].execute(sql) grade_12_students.collect do |array| Student.new.tap do |s| s.id = array[0] s.name = array[1] s.grade = array[2] end end end def self.first_student_in_grade_10 sql = <<-SQL SELECT * FROM students WHERE grade = 10 LIMIT 1 SQL grade_10_student = DB[:conn].execute(sql)[0] Student.new( grade_10_student[0], grade_10_student[1], grade_10_student[2] ) end def initialize(id=nil, name=nil, grade=nil) @id = id @name = name @grade = grade end def self.find_by_name(name) sql = <<-SQL SELECT * FROM students WHERE students.name = name SQL student_info = DB[:conn].execute(sql)[0] Student.new( student_info[0], student_info[1], student_info[2] ) end def save sql = <<-SQL INSERT INTO students (name, grade) VALUES (?, ?) SQL DB[:conn].execute(sql, self.name, self.grade) end def self.create_table sql = <<-SQL CREATE TABLE IF NOT EXISTS students ( id INTEGER PRIMARY KEY, name TEXT, grade TEXT ) SQL DB[:conn].execute(sql) end def self.drop_table sql = "DROP TABLE IF EXISTS students" DB[:conn].execute(sql) end end
class CreatePages < ActiveRecord::Migration def change create_table :pages do |t| t.string :title t.integer :parent_id t.string :custom_title t.boolean :display_in_menu t.string :browser_title t.string :meta_keywords t.text :meta_desc t.boolean :draft t.timestamps end end end
class Plan < ActiveRecord::Base belongs_to :user belongs_to :level belongs_to :category end
require 'uri' require 'uriparser' # wrapper the ruby URI class module URI def self.parser uri UriParser.parse(uri) end end module Kernel def URI(uri) UriParser.parse(uri) end end
require 'csv' namespace :import do desc "Import Churches from CSV" task :organizations, [:filename] => [:environment] do |t, args| campaign = Campaign.find_or_create_by( name: 'Serve Day', description: 'Serve Day', status: 'open' ) filename = File.join(Rails.root, 'tmp', args[:filename]) CSV.foreach(filename) do |row| name, address1, city, state, zip, country, first_name, last_name, email, phone, subdomain = row if Organization.find_by_subdomain(subdomain) next else puts "Importing #{name}" organization = Organization.create!(name: name, description: name, address1: address1, city: city, country: country, state: state, zip: zip, email: email, phone: phone, subdomain: subdomain, accent_color: "#3E3E3E", status: 'approved') puts organization.errors.full_messages.join(',') if organization.errors.any? puts "Imported #{name}" if organization.persisted? puts "Creating Serve Day 2018 event for: #{organization.name}" event = organization.events.find_or_create_by( campaign_id: Campaign.first.id, name: "Serve Day 2018 - #{organization.name}" ) event.update_attributes( description: 'Serve Day July, 14th 2018', start_date: DateTime.new(2018, 7, 14, 0, 0, 0), end_date: DateTime.new(2018, 7, 14, 23, 59, 59), open_date: DateTime.new(2018, 5, 28, 0, 0, 0), close_date: DateTime.new(2018, 7, 14, 23, 59, 59), accent_color: "#3E3E3E", hashtag: "##{event.slug}", status: 'active' ) puts "Created Event: #{event.name}" project = event.projects.create!( user_id: 1, name: 'Project Setup', description: 'Set up a project', status: 'pending', people_needed: 1, start_date: event.start_date, end_date: event.end_date, city: event.organization.city, state: event.organization.state, zip: event.organization.zip, latitude: event.organization.latitude, longitude: event.organization.longitude, accessible: false, address1: event.organization.address1, address2: event.organization.address2, walk_ons: 0 ) puts "Creating Project: #{project.name}" end end end end
class CreateQaAnswers < ActiveRecord::Migration def self.up create_table :qa_answers do |t| t.integer :question_id t.text :text, :limit => 15000, :null => false t.timestamps end end def self.down drop_table :qa_answers end end
class MeetupEventsController < ApplicationController before_action :check_user before_action :set_event, only: [:show, :edit, :update, :destroy] def index @meetup_event = MeetupEvent.first redirect_to new_meetup_event_url unless @meetup_event.present? end def new redirect_to edit_meetup_event_url(MeetupEvent.last) if MeetupEvent.last.present? @meetup_event = MeetupEvent.new end def create @meetup_event = MeetupEvent.new(meetup_event_params) respond_to do |format| if @meetup_event.save format.html { redirect_to meetup_events_url, flash: {success: "#{@meetup_event.title} was successfully created."} } format.json { render :show, status: :created, location: @meetup_event } else format.html { render :new } format.json { render json: @meetup_event.errors, status: :unprocessable_entity } end end end def edit end def update respond_to do |format| if @meetup_event.update(meetup_event_params) format.html { redirect_to meetup_events_url, flash: {success: "#{@meetup_event.title} was successfully updated."} } format.json { render :show, status: :ok, location: @meetup_event } else format.html { render :edit } format.json { render json: @meetup_event.errors, status: :unprocessable_entity } end end end def show end def destroy end private def set_event @meetup_event = MeetupEvent.find(params[:id]) end def check_user redirect_to root_url unless current_user.present? && current_user.admin end def meetup_event_params params.require(:meetup_event).permit(:title, :description, :status, :meetup_image, :url) end end
require './Lib/weather' class Airport include Weather def initialize(gates=[]) @gates = gates @holding_pattern = [] end attr_reader :gates, :holding_pattern def approach plane if !full? && clear_to_fly? clear_to_land plane next_gate.dock plane else hold_plane plane end end def depart gate return unless clear_to_fly? departing_plane = gate.undock clear_to_take_off departing_plane end def weather_conditions location location.current_conditions end def available_gates gates.select{|g| g.available?} end def full_gates gates.reject{|g| g.available?} end def next_gate available_gates.first end def full? available_gates.count == 0 end def clear_to_land plane plane.land end def clear_to_take_off plane plane.take_off end def hold_plane plane holding_pattern << plane end def unhold_plane plane holding_pattern.delete(plane) end end
class CreateShareAStats < ActiveRecord::Migration def change create_table :share_a_stats do |t| t.string :title t.text :message t.string :image t.boolean :scholarship t.string :tip t.integer :mc_alpha t.integer :mc_beta t.string :redirect t.text :redirect_message t.integer :campaign_id t.string :color_scheme t.string :logo t.string :logo_text t.string :shortform_image t.string :shortform_bucket t.string :sponsor_image t.boolean :published t.timestamps end end end
module SQLite3 class Encoding class << self def find(encoding) enc = encoding.to_s if enc.downcase == "utf-16" utf_16native else ::Encoding.find(enc).tap do |e| if utf_16?(e) && e != utf_16native raise ArgumentError, "requested to use byte order different than native" end end end end def utf_16?(str_or_enc) enc = str_or_enc.kind_of?(::Encoding) ? str_or_enc : str_or_enc.encoding [utf_16le, utf_16be].include?(enc) end def utf_16native "Ruby".unpack("i")[0] == 2036495698 ? utf_16le : utf_16be end def us_ascii ::Encoding::US_ASCII end def utf_8 ::Encoding::UTF_8 end def utf_16le ::Encoding::UTF_16LE end def utf_16be ::Encoding::UTF_16BE end end end end
class Specinfra::Command::Linux::Base::Interface < Specinfra::Command::Base::Interface class << self def check_exists(name) "ip link show #{name}" end def get_speed_of(name) "cat /sys/class/net/#{name}/speed" end def check_has_ipv4_address(interface, ip_address) ip_address = ip_address.dup if ip_address =~ /\/\d+$/ ip_address << " " else ip_address << "/" end ip_address.gsub!(".", "\\.") "ip -4 addr show #{interface} | grep 'inet #{ip_address}'" end def check_has_ipv6_address(interface, ip_address) ip_address = ip_address.dup if ip_address =~ /\/\d+$/ ip_address << " " else ip_address << "/" end ip_address.downcase! "ip -6 addr show #{interface} | grep 'inet6 #{ip_address}'" end def get_link_state(name) "cat /sys/class/net/#{name}/operstate" end end end
module Admin::UsersHelper def status(user) return user.banned ? "Banned" : "Ok" end def role(user) return user.admin ? "Admin" : "User" end def ban_btn_text(user) return user.banned ? "Unban" : "Ban" end end
class User < ApplicationRecord # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable has_one :verification, dependent: :destroy has_many :properties, dependent: :destroy validates :email, :password, :name, :phone_number, presence: true, on: :create validates :email, format: {with: URI::MailTo::EMAIL_REGEXP} validates_uniqueness_of :email validates_uniqueness_of :phone_number validates_format_of :phone_number, with: /\A(\+?\d{1,3})?\d{10}\z/, message: "- Phone number must be in +XXXXXXXXXXXX format" enum role: [:buyer, :seller] scope :buyer, -> {where(role: :buyer)} scope :seller, -> {where(role: :seller)} has_one_attached :avatar validate :check_file_type ,if: :avatar_attached def check_file_type if avatar.content_type.in?(%w(image/gif image/png image/jpg image/jpeg)) return true else errors.add(:avatar, "Must be a GIF/JPG/PNG file") end end def avatar_attached avatar.attched? end # has_attached_file :avatar, style: { medium: "300X300", thumb: "50X50" }, default_url: "avatar.png" # validates_attachment_content_type :avatar, content_type: ["image/jpeg", "image/gif", "image/png"] # devise :omniauthable, omaniauth_providers: [:google_oauth2] end
require_relative("../db/sql_runner") require_relative("customer.rb") require_relative("film.rb") require_relative("ticket.rb") class Screening attr_reader :id attr_accessor :film_id, :time_slot, :capacity def initialize(details) @id = details['id'].to_i() if details['id'] @film_id = details['film_id'].to_i() @time_slot = details['time_slot'] @capacity = details['capacity'].to_i() end def save() @id = SqlRunner.run("INSERT INTO screenings (film_id, time_slot, capacity) VALUES ($1, $2, $3) RETURNING id;", [@film_id, @time_slot, @capacity])[0]['id'].to_i() end def self.all() return SqlRunner.run("SELECT * FROM screenings;").map() { |screening| Screening.new( screening ) } end def self.delete_all() SqlRunner.run("DELETE FROM screenings;") end def update() SqlRunner.run("UPDATE screenings SET (film_id, time_slot, capacity) = ($1, $2, $3) WHERE id = $4;", [@film_id, @time_slot, @capacity, @id]) end def delete() SqlRunner.run("DELETE FROM screenings where id = $1;", [@id]) end def self.find(id) result = (SqlRunner.run("SELECT * FROM screenings WHERE id = $1;", [id]).first()) return Screening.new(result) if (result != nil) end def film() return Film.new(SqlRunner.run("SELECT * FROM films WHERE id = $1;", [@film_id])[0]) end def customers() return SqlRunner.run("SELECT customers.* FROM tickets INNER JOIN customers ON tickets.customer_id = customers.id WHERE tickets.screening_id = $1;", [@id]).uniq().map() { |customer| Customer.new(customer) } end def customer_count() return self.customers.count() end def tickets() return SqlRunner.run("SELECT * FROM tickets WHERE screening_id = $1;", [@id]).map() { |ticket| Ticket.new(ticket) } end def ticket_count() return self.tickets.count() end end
class MissedVisitReminderService def self.send_after_missed_visit(*args) new(*args).send_after_missed_visit end def initialize(appointments:, days_overdue: 3) @appointments = appointments @days_overdue = days_overdue @communication_type = if Flipper.enabled?(:whatsapp_appointment_reminders) Communication.communication_types[:whatsapp] else Communication.communication_types[:sms] end end def send_after_missed_visit eligible_appointments = appointments.eligible_for_reminders(days_overdue: days_overdue) next_messaging_time = Communication.next_messaging_time eligible_appointments.each do |appointment| notification = create_reminder(appointment, remind_on: next_messaging_time) AppointmentNotification::Worker.perform_at(next_messaging_time, notification.id) end end private def create_reminder(appointment, remind_on:) Notification.create!( subject: appointment, patient: appointment.patient, remind_on: remind_on, status: "scheduled", message: "communications.appointment_reminders.#{communication_type}", purpose: "missed_visit_reminder" ) end attr_reader :appointments, :communication_type, :days_overdue end
# class to help manage user sessions class UserSession # receive a list of posible user ids, return de first that's not nil def self.get_user_session_id(user_sessions) user_sessions.each do |user_session| return user_session unless user_session.nil? end end end
# encoding: UTF-8 module OmniSearch # Indexes::Plaintext class Indexes::Plaintext < Indexes::Base STORAGE_ENGINE = Indexes::Storage::Plaintext end end
require 'player' describe Player do subject(:player1) { Player.new('Kavita') } subject(:player2) { Player.new('Prabu') } it 'returns player name' do expect(player1.name).to eq 'Kavita' end it 'returns player hitpoints' do expect(player1.hit_points).to eq Player::DEFAULT_HP end it 'reduces hitpoint of player when attacked' do expect { player2.receive_damage(10) }.to change { player2.hit_points }.by(-10) end end
module ExceptionHub class ExceptionStorage def perform(exception, env) storage = ExceptionHub.storage.new storage.save(storage.find(exception.filtered_message), {:message => exception.message, :backtrace => exception.formatted_backtrace}) self end end end
#encoding=utf-8 require 'spec_helper' describe NonconformingProduct do let(:nonconforming_product) { } describe "Validations" do it { should validate_presence_of(:issue) } it { should validate_presence_of(:description) } end describe "Associations" do it { should belong_to(:user) } end describe "notify new nonconforming product" do before(:each) do @np = FactoryGirl.build(:nonconforming_product) @message = mock("NonconformingProductNotifier", deliver: true) NonconformingProductNotifier.stub!(:new_nonconforming_product_message). and_return(@message) end it "should notiy to users from company the new nonconforming product" do @message.should_receive(:deliver) @np.save end end end
class RemoveColumnCoverUrlFromUsers < ActiveRecord::Migration def change remove_column :users, :cover_photo, :string end end
module Comercio module Address class Address < SitePrism::Page def is_address is_visible_el 'address.is_address' end def click_buy click_el 'address.buy' end def choose_delivery delivery_type delivery_type.downcase! unless delivery_type == 'default' if delivery_type == 'random' click_el_random 'address.shipping_type' else if IOS case delivery_type.downcase! when 'normal' el = 'address.shipping_normal_ios' when 'agendada' el = 'address.shipping_agendada_ios' when 'expressa' el = 'address.shipping_expressa_ios' when 'super_expressa' el = 'address.shipping_super_expressa_ios' end unless is_visible_el el swipe_page_x end click_el el else els = find_all_els 'address.shipping_type' element = check_delivery els, delivery_type if element.nil? swipe_page_x els = find_all_els 'address.shipping_type' element = check_delivery els, delivery_type end if element.nil? false else element.click if delivery_type == 'agendada' set_agendada end true end end end end end private def set_agendada tap_el 'address.open_schedule_date_list' click_el_random 'address.open_schedule_date_option' tap_el 'address.open_schedule_hour_list' click_el_random 'address.open_schedule_hour_option' end def check_delivery els, delivery_type element = nil els.each do |el| if el.text.downcase.include? delivery_type element = el break end end element end end end end
class SessionsController < ApplicationController def new @user = User.new end def create if auth user = User.find_or_create_by_omniauth(auth) current_user(user) associate_cart_items_to_user redirect_to root_path else user = User.find_by(email: user_params[:email]) if user && user.authenticate(user_params[:password]) current_user(user) associate_cart_items_to_user if !current_cart.empty? redirect_to cart_path else redirect_to root_path end else flash[:message] = "* Incorrect login information" redirect_to login_path end end end def destroy if current_user clear_cart session.delete :user_id end redirect_to '/' end private def auth request.env["omniauth.auth"] end end
class KindsController < ApplicationController def show @snippets = Snippet.where("kind_id= ? AND is_private = ?", params[:id], false) end end
class Hangman DICTIONARY = ["cat", "dog", "bootcamp", "pizza"] end
require 'test_helper' class QuestionTest < ActiveSupport::TestCase test "should not save question without body and assigned_part" do question = Question.new assert !question.save, "Saved the question without a body" end end
class AddDescriptionToMessage < ActiveRecord::Migration def change add_column :messages, :to, :string, array: true, default: "{}" end end
module Monkeyshines module RequestStream # # Watch for jobs in an Edamame priority queue # (http://mrflip.github.com/edamame) # class EdamameQueue < Edamame::Broker # How long to wait for tasks cattr_accessor :queue_request_timeout self.queue_request_timeout = 5 * 60 # seconds # priority for search jobs if not otherwise given QUEUE_PRIORITY = 65536 def initialize _options tube = Monkeyshines::CONFIG[:handle].to_s.gsub(/_/, '-') super _options.deep_merge( :tube => tube ) if _options[:queue_request_timeout] Log.info "Setting timeout to #{_options[:queue_request_timeout]}" self.queue_request_timeout = _options[:queue_request_timeout] end end # def each klass, &block # work(queue_request_timeout, klass) do |job| # job.each_request(&block) # end # Log.info [queue, queue.beanstalk_stats] # end def each &block work(queue_request_timeout) do |job| yield job.obj['type'], job.obj end Log.info [queue, queue.beanstalk_stats] end def req_to_job req, job_options={} obj_hash = req.to_hash.merge( 'type' => req.class.to_s, 'key' => [req.class.to_s, req.key].join('-') ) Edamame::Job.from_hash(job_options.merge("obj" => obj_hash, 'priority' => (66000 + 1000*req.req_generation), 'tube' => tube )) end def put job, *args job_options = args.extract_options! job = req_to_job(job, job_options) unless job.is_a?(Beanstalk::Job) || job.is_a?(Edamame::Job) # p [self.class, job.key, job.obj,job.scheduling, job_options, args] super job, *args end end end end
class OCR # :nodoc: attr_reader :text NUMBER_HEIGHT = 4 NUMBER_WIDTH = 3 NUMBERS = { ' _ | ||_|' => '0', ' | |' => '1', ' _ _||_ ' => '2', ' _ _| _|' => '3', ' |_| |' => '4', ' _ |_ _|' => '5', ' _ |_ |_|' => '6', ' _ | |' => '7', ' _ |_||_|' => '8', ' _ |_| _|' => '9' }.freeze def initialize(text) @text = text end def convert return parse_single_digit(text) if single_digit? return parse_multi_line(text) if multi_line? parse_multi_digit(text) end private def single_digit? text.split("\n").first.size <= NUMBER_WIDTH end def multi_line? text.match("\n\n") end def parse_single_digit(digit) result = digit.split("\n").map { |part| standardize(part) }.join NUMBERS[result] || '?' end def parse_multi_digit(digits_in_line) parse_digits(digits_in_line) .map { |digit| parse_single_digit(digit) } .join end def parse_digits(digits_in_line) result = [] digits_in_line.split("\n").each do |line| line.scan(/.{1,#{NUMBER_WIDTH}}/).each_with_index do |part, idx| result[idx] ||= '' result[idx] << standardize(part) end end result end def parse_multi_line(lines) lines.split("\n\n") .map { |line| parse_multi_digit(line) } .join(',') end def standardize(part) if part == ' _' part = ' _ ' elsif part == '' part = ' ' elsif part == '|_' part = '|_ ' else part end end end
class ClientsController < ResourceController protected def collection @clients ||= end_of_association_chain.includes(:client_logo, :projects, :images, :services) end end
class AddScheduleTable < ActiveRecord::Migration def change create_table :schedule do |t| t.column :day, :string t.column :hours, :string end remove_column :appointments, :practitioner_id, :int remove_column :services, :practitioner_id, :int end end
require 'rails_helper' describe Style do describe "#dress?" do context "type is dress" do let(:style) { FactoryGirl.create(:style, type: "Dress") } it "should return true" do expect(style.dress?).to eq(true) end end context "type is not dress" do let(:style) { FactoryGirl.create(:style, type: "Sweater") } it "should return false" do expect(style.dress?).to eq(false) end end end describe "#pants?" do context "type is pants" do let(:style) { FactoryGirl.create(:style, type: "Pants") } it "should return true" do expect(style.pants?).to eq(true) end end context "type is not pants" do let(:style) { FactoryGirl.create(:style, type: "Top") } it "should return false" do expect(style.pants?).to eq(false) end end end end
# frozen_string_literal: true class Movie < ApplicationRecord has_many :movie_genres has_many :genres, through: :movie_genres has_many :movie_directors has_many :directors, through: :movie_directors has_many :movie_creators has_many :creators, through: :movie_creators has_many :movie_cast_members has_many :cast_members, through: :movie_cast_members has_many :movie_keywords has_many :keywords, through: :movie_keywords def update_search movie_search = MoviesSearch.find_or_initialize_by(id: id) search_content = "#{name}; #{brief_description}; #{cast_members.pluck(:name).join(', ')}; " \ "#{creators.pluck(:name).join(', ')}; #{directors.pluck(:name).join(', ')}; " \ "#{genres.pluck(:name).join(', ')}; #{keywords.pluck(:name).join(', ')}" return if movie_search.update(search_content: search_content) Rails.logger.warn("Unable to update the search cache for movie #{id}. Please re-trigger the update for this movie.") end end
RSpec.describe Dota::API::MissingHero do let(:hero) { described_class.new(nil) } specify "#id" do expect(hero.id).to eq nil end specify "#name" do expect(hero.name).to eq nil end specify "#image_url" do expect(hero.image_url).to eq nil expect(hero.image_url(:something)).to eq nil end end
class ApplicationController < ActionController::Base protect_from_forgery with: :exception before_action :configure_permitted_parameters, if: :devise_controller? rescue_from CanCan::AccessDenied do |exception| respond_to do |format| format.json { head :forbidden, content_type: 'text/html' } format.html { redirect_to main_app.root_url, notice: exception.message } format.js { head :forbidden, content_type: 'text/html' } end end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up) do |user| user.permit(:email, :password,:password_confirmation, :remember_me,:first,:last,:code) end devise_parameter_sanitizer.permit(:account_update) do |user| user.permit(:email, :password,:password_confirmation, :current_password,:first,:last,:code) end end end
class RenameSalerIdColumnToItems < ActiveRecord::Migration[5.2] def change rename_column :items, :saler_id, :seller_id end end
# frozen_string_literal: true # rubocop:todo all # Copyright (C) 2014-2020 MongoDB Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo module Grid # Represents a view of the GridFS in the database. # # @since 2.0.0 class FSBucket extend Forwardable # The default root prefix. # # @since 2.0.0 DEFAULT_ROOT = 'fs'.freeze # The specification for the chunks collection index. # # @since 2.0.0 CHUNKS_INDEX = { :files_id => 1, :n => 1 }.freeze # The specification for the files collection index. # # @since 2.1.0 FILES_INDEX = { filename: 1, uploadDate: 1 }.freeze # Create the GridFS. # # @example Create the GridFS. # Grid::FSBucket.new(database) # # @param [ Database ] database The database the files reside in. # @param [ Hash ] options The GridFS options. # # @option options [ String ] :bucket_name The prefix for the files and chunks # collections. # @option options [ Integer ] :chunk_size Override the default chunk # size. # @option options [ String ] :fs_name The prefix for the files and chunks # collections. # @option options [ Hash ] :read The read preference options. The hash # may have the following items: # - *:mode* -- read preference specified as a symbol; valid values are # *:primary*, *:primary_preferred*, *:secondary*, *:secondary_preferred* # and *:nearest*. # - *:tag_sets* -- an array of hashes. # - *:local_threshold*. # @option options [ Session ] :session The session to use. # @option options [ Hash ] :write Deprecated. Equivalent to :write_concern # option. # @option options [ Hash ] :write_concern The write concern options. # Can be :w => Integer|String, :fsync => Boolean, :j => Boolean. # # @since 2.0.0 def initialize(database, options = {}) @database = database @options = options.dup =begin WriteConcern object support if @options[:write_concern].is_a?(WriteConcern::Base) # Cache the instance so that we do not needlessly reconstruct it. @write_concern = @options[:write_concern] @options[:write_concern] = @write_concern.options end =end @options.freeze @chunks_collection = database[chunks_name] @files_collection = database[files_name] end # @return [ Collection ] chunks_collection The chunks collection. # # @since 2.0.0 attr_reader :chunks_collection # @return [ Database ] database The database. # # @since 2.0.0 attr_reader :database # @return [ Collection ] files_collection The files collection. # # @since 2.0.0 attr_reader :files_collection # @return [ Hash ] options The FSBucket options. # # @since 2.1.0 attr_reader :options # Get client from the database. # # @since 2.1.0 def_delegators :database, :client # Find files collection documents matching a given selector. # # @example Find files collection documents by a filename. # fs.find(filename: 'file.txt') # # @param [ Hash ] selector The selector to use in the find. # @param [ Hash ] options The options for the find. # # @option options [ true, false ] :allow_disk_use Whether the server can # write temporary data to disk while executing the find operation. # @option options [ Integer ] :batch_size The number of documents returned in each batch # of results from MongoDB. # @option options [ Integer ] :limit The max number of docs to return from the query. # @option options [ true, false ] :no_cursor_timeout The server normally times out idle # cursors after an inactivity period (10 minutes) to prevent excess memory use. # Set this option to prevent that. # @option options [ Integer ] :skip The number of docs to skip before returning results. # @option options [ Hash ] :sort The key and direction pairs by which the result set # will be sorted. # # @return [ CollectionView ] The collection view. # # @since 2.1.0 def find(selector = nil, options = {}) opts = options.merge(read: read_preference) if read_preference files_collection.find(selector, opts || options) end # Find a file in the GridFS. # # @example Find a file by its id. # fs.find_one(_id: id) # # @example Find a file by its filename. # fs.find_one(filename: 'test.txt') # # @param [ Hash ] selector The selector. # # @return [ Grid::File ] The file. # # @since 2.0.0 # # @deprecated Please use #find instead with a limit of -1. # Will be removed in version 3.0. def find_one(selector = nil) file_info = files_collection.find(selector).first return nil unless file_info chunks = chunks_collection.find(:files_id => file_info[:_id]).sort(:n => 1) Grid::File.new(chunks.to_a, Options::Mapper.transform(file_info, Grid::File::Info::MAPPINGS.invert)) end # Insert a single file into the GridFS. # # @example Insert a single file. # fs.insert_one(file) # # @param [ Grid::File ] file The file to insert. # # @return [ BSON::ObjectId ] The file id. # # @since 2.0.0 # # @deprecated Please use #upload_from_stream or #open_upload_stream instead. # Will be removed in version 3.0. def insert_one(file) @indexes ||= ensure_indexes! chunks_collection.insert_many(file.chunks) files_collection.insert_one(file.info) file.id end # Get the prefix for the GridFS # # @example Get the prefix. # fs.prefix # # @return [ String ] The GridFS prefix. # # @since 2.0.0 def prefix @options[:fs_name] || @options[:bucket_name] || DEFAULT_ROOT end # Remove a single file from the GridFS. # # @example Remove a file from the GridFS. # fs.delete_one(file) # # @param [ Grid::File ] file The file to remove. # # @return [ Result ] The result of the remove. # # @since 2.0.0 def delete_one(file) delete(file.id) end # Remove a single file, identified by its id from the GridFS. # # @example Remove a file from the GridFS. # fs.delete(id) # # @param [ BSON::ObjectId, Object ] id The id of the file to remove. # # @return [ Result ] The result of the remove. # # @raise [ Error::FileNotFound ] If the file is not found. # # @since 2.1.0 def delete(id) result = files_collection.find({ :_id => id }, @options).delete_one chunks_collection.find({ :files_id => id }, @options).delete_many raise Error::FileNotFound.new(id, :id) if result.n == 0 result end # Opens a stream from which a file can be downloaded, specified by id. # # @example Open a stream from which a file can be downloaded. # fs.open_download_stream(id) # # @param [ BSON::ObjectId, Object ] id The id of the file to read. # @param [ Hash ] options The options. # # @option options [ BSON::Document ] :file_info_doc For internal # driver use only. A BSON document to use as file information. # # @return [ Stream::Read ] The stream to read from. # # @yieldparam [ Hash ] The read stream. # # @since 2.1.0 def open_download_stream(id, options = nil) options = Utils.shallow_symbolize_keys(options || {}) read_stream(id, **options).tap do |stream| if block_given? begin yield stream ensure stream.close end end end end # Downloads the contents of the file specified by id and writes them to # the destination io object. # # @example Download the file and write it to the io object. # fs.download_to_stream(id, io) # # @param [ BSON::ObjectId, Object ] id The id of the file to read. # @param [ IO ] io The io object to write to. # # @since 2.1.0 def download_to_stream(id, io) open_download_stream(id) do |stream| stream.each do |chunk| io << chunk end end end # Opens a stream from which the application can read the contents of the stored file # specified by filename and the revision in options. # # Revision numbers are defined as follows: # 0 = the original stored file # 1 = the first revision # 2 = the second revision # etc… # -2 = the second most recent revision # -1 = the most recent revision # # @example Open a stream to download the most recent revision. # fs.open_download_stream_by_name('some-file.txt') # # # @example Open a stream to download the original file. # fs.open_download_stream_by_name('some-file.txt', revision: 0) # # @example Open a stream to download the second revision of the stored file. # fs.open_download_stream_by_name('some-file.txt', revision: 2) # # @param [ String ] filename The file's name. # @param [ Hash ] opts Options for the download. # # @option opts [ Integer ] :revision The revision number of the file to download. # Defaults to -1, the most recent version. # # @return [ Stream::Read ] The stream to read from. # # @raise [ Error::FileNotFound ] If the file is not found. # @raise [ Error::InvalidFileRevision ] If the requested revision is not found for the file. # # @yieldparam [ Hash ] The read stream. # # @since 2.1.0 def open_download_stream_by_name(filename, opts = {}, &block) revision = opts.fetch(:revision, -1) if revision < 0 skip = revision.abs - 1 sort = { 'uploadDate' => Mongo::Index::DESCENDING } else skip = revision sort = { 'uploadDate' => Mongo::Index::ASCENDING } end file_info_doc = files_collection.find({ filename: filename} , sort: sort, skip: skip, limit: -1).first unless file_info_doc raise Error::FileNotFound.new(filename, :filename) unless opts[:revision] raise Error::InvalidFileRevision.new(filename, opts[:revision]) end open_download_stream(file_info_doc[:_id], file_info_doc: file_info_doc, &block) end # Downloads the contents of the stored file specified by filename and by the # revision in options and writes the contents to the destination io object. # # Revision numbers are defined as follows: # 0 = the original stored file # 1 = the first revision # 2 = the second revision # etc… # -2 = the second most recent revision # -1 = the most recent revision # # @example Download the most recent revision. # fs.download_to_stream_by_name('some-file.txt', io) # # # @example Download the original file. # fs.download_to_stream_by_name('some-file.txt', io, revision: 0) # # @example Download the second revision of the stored file. # fs.download_to_stream_by_name('some-file.txt', io, revision: 2) # # @param [ String ] filename The file's name. # @param [ IO ] io The io object to write to. # @param [ Hash ] opts Options for the download. # # @option opts [ Integer ] :revision The revision number of the file to download. # Defaults to -1, the most recent version. # # @raise [ Error::FileNotFound ] If the file is not found. # @raise [ Error::InvalidFileRevision ] If the requested revision is not found for the file. # # @since 2.1.0 def download_to_stream_by_name(filename, io, opts = {}) download_to_stream(open_download_stream_by_name(filename, opts).file_id, io) end # Opens an upload stream to GridFS to which the contents of a file or # blob can be written. # # @param [ String ] filename The name of the file in GridFS. # @param [ Hash ] opts The options for the write stream. # # @option opts [ Object ] :file_id An optional unique file id. # A BSON::ObjectId is automatically generated if a file id is not # provided. # @option opts [ Integer ] :chunk_size Override the default chunk size. # @option opts [ Hash ] :metadata User data for the 'metadata' field of the files # collection document. # @option opts [ String ] :content_type The content type of the file. # Deprecated, please use the metadata document instead. # @option opts [ Array<String> ] :aliases A list of aliases. # Deprecated, please use the metadata document instead. # @option options [ Hash ] :write Deprecated. Equivalent to :write_concern # option. # @option options [ Hash ] :write_concern The write concern options. # Can be :w => Integer|String, :fsync => Boolean, :j => Boolean. # # @return [ Stream::Write ] The write stream. # # @yieldparam [ Hash ] The write stream. # # @since 2.1.0 def open_upload_stream(filename, opts = {}) opts = Utils.shallow_symbolize_keys(opts) write_stream(filename, **opts).tap do |stream| if block_given? begin yield stream ensure stream.close end end end end # Uploads a user file to a GridFS bucket. # Reads the contents of the user file from the source stream and uploads it as chunks in the # chunks collection. After all the chunks have been uploaded, it creates a files collection # document for the filename in the files collection. # # @example Upload a file to the GridFS bucket. # fs.upload_from_stream('a-file.txt', file) # # @param [ String ] filename The filename of the file to upload. # @param [ IO ] io The source io stream to upload from. # @param [ Hash ] opts The options for the write stream. # # @option opts [ Object ] :file_id An optional unique file id. An ObjectId is generated otherwise. # @option opts [ Integer ] :chunk_size Override the default chunk size. # @option opts [ Hash ] :metadata User data for the 'metadata' field of the files # collection document. # @option opts [ String ] :content_type The content type of the file. Deprecated, please # use the metadata document instead. # @option opts [ Array<String> ] :aliases A list of aliases. Deprecated, please use the # metadata document instead. # @option options [ Hash ] :write Deprecated. Equivalent to :write_concern # option. # @option options [ Hash ] :write_concern The write concern options. # Can be :w => Integer|String, :fsync => Boolean, :j => Boolean. # # @return [ BSON::ObjectId ] The ObjectId file id. # # @since 2.1.0 def upload_from_stream(filename, io, opts = {}) open_upload_stream(filename, opts) do |stream| begin stream.write(io) # IOError and SystemCallError are for errors reading the io. # Error::SocketError and Error::SocketTimeoutError are for # writing to MongoDB. rescue IOError, SystemCallError, Error::SocketError, Error::SocketTimeoutError begin stream.abort rescue Error::OperationFailure end raise end end.file_id end # Get the read preference. # # @note This method always returns a BSON::Document instance, even though # the FSBucket constructor specifies the type of :read as a Hash, not # as a BSON::Document. # # @return [ BSON::Document ] The read preference. # The document may have the following fields: # - *:mode* -- read preference specified as a symbol; valid values are # *:primary*, *:primary_preferred*, *:secondary*, *:secondary_preferred* # and *:nearest*. # - *:tag_sets* -- an array of hashes. # - *:local_threshold*. def read_preference @read_preference ||= begin pref = options[:read] || database.read_preference if BSON::Document === pref pref else BSON::Document.new(pref) end end end # Get the write concern. # # @example Get the write concern. # stream.write_concern # # @return [ Mongo::WriteConcern ] The write concern. # # @since 2.1.0 def write_concern @write_concern ||= if wco = @options[:write_concern] || @options[:write] WriteConcern.get(wco) else database.write_concern end end private # @param [ Hash ] opts The options. # # @option opts [ BSON::Document ] :file_info_doc For internal # driver use only. A BSON document to use as file information. def read_stream(id, **opts) Stream.get(self, Stream::READ_MODE, { file_id: id }.update(options).update(opts)) end def write_stream(filename, **opts) Stream.get(self, Stream::WRITE_MODE, { filename: filename }.update(options).update(opts)) end def chunks_name "#{prefix}.#{Grid::File::Chunk::COLLECTION}" end def files_name "#{prefix}.#{Grid::File::Info::COLLECTION}" end def ensure_indexes! if files_collection.find({}, limit: 1, projection: { _id: 1 }).first.nil? create_index_if_missing!(files_collection, FSBucket::FILES_INDEX) end if chunks_collection.find({}, limit: 1, projection: { _id: 1 }).first.nil? create_index_if_missing!(chunks_collection, FSBucket::CHUNKS_INDEX, :unique => true) end end def create_index_if_missing!(collection, index_spec, options = {}) indexes_view = collection.indexes begin if indexes_view.get(index_spec).nil? indexes_view.create_one(index_spec, options) end rescue Mongo::Error::OperationFailure => e # proceed with index creation if a NamespaceNotFound error is thrown if e.code == 26 indexes_view.create_one(index_spec, options) else raise end end end end end end
class ExtendedRegister4 < DLMSClass defineAttribute("logical_name") defineAttribute("data") defineAttribute("scaler_unit") defineMethod("reset") end module DLMSTrouble class DLMSClass VERSIONED_NAME_REGEX = /^(?<name>([A-Z][A-Za-z0-9]*))CID(?<classID>[0-9]+)V(?<version>[0-9]+)$/ NAME_REGEX = /^(?<name>([A-Z][A-Za-z0-9]*))CID(?<classID>[0-9]+)$/ def self.inherited(subclass) subclass.defineClass super end # @param classVersion [Integer] Class Version def self.defineClass #if !classID.is_a? Integer or classID > CLASS_ID_MAX; raise ArgumentError.new "classID must be an Integer in the range (0..#{CLASS_ID_MAX})" end name = self.name.split('::').last match = VERSIONED_NAME_REGEX.match(name) if match @classVersion = match[:version].to_i @className = match[:name] @classID = match[:classID] else match = NAME_REGEX.match(name) if match @classVersion = 0 @className = match[:name] @classID = match[:classID] else raise "class name '#{name}' must be meet requirements" end end if @classVersion > CLASS_VERSION_MAX; raise ArgumentError.new "classVersion must be an Integer in the range (0..#{CLASS_VERSION_MAX})" end @methodByName = {} @methodByIndex = {} end # @return [String] def self.className; return @className end # @return [Integer] def self.classID; return @classID end # @return [Integer] def self.classVersion; return @classVersion end # @param [String,Integer] # @return [Hash] attribute descriptor def self.attribute(id=nil) if id.nil? @attrByName.values elsif id.kind_of? String @attrByName[id] else @attrByIndex[id.to_i] end end def self.method(id) if id.kind_of? String @methByName[id] else @methByIndex[id.to_i] end end def self.defineAttribute(name, **opts) id = opts[:attributeID] if id if id.to_i > 127 or id.to_i < -128; raise ArgumentError end else id = 1 @attrs.each do |attr| if attr[:attrID] end def self.defineMethod(name, **opts) id = opts[:methodID] end def self.defineMethod(methodName, opts = {}) methodIndex = opts[:methodIndex] if !methodName.is_a? String; raise ArgumentError.new "methodName '#{methodName}' is not [String]"end if !methodIndex.nil? and ( !methodIndex.is_a? Integer or methodIndex > METHOD_INDEX_MAX); raise ArgumentError.new "opts[:methodIndex] '#{methodIndex}' is not [Integer] in range (0..#{METHOD_INDEX_MAX})" end if methodIndex.nil? if @methodByIndex.size == 0; methodIndex = 0 else methodIndex = @methodByIndex.keys.last + 1 end if methodIndex > METHOD_INDEX_MAX; raise Exception "Implicitly allocated methodIndex is exhausted at method definition '#{methodName}'" end else if !methodByIndex[methodIndex].nil?; raise Exception "opts[:methodIndex] `#{methodIndex}` is already allocated to method `#{@methodByIndex[methodIndex][:methodName]}`" end end if @methodByName[methodName]; raise "Method '#{methodName}' is already defined" end @methodByName[methodName] = { :methodName => methodName, :methodIndex => methodIndex, :description => opts[:description], :argument => opts[:argument], :returnValue => opts[:returnValue] } @methodByIndex[methodIndex] = @methodByName[methodName] end end end
class CreateNews < ActiveRecord::Migration[5.0] def change create_table :news do |t| t.string :title, null: false t.string :description, null: false t.datetime :published_at t.boolean :published t.string :url t.timestamps end end end
class Stack attr_accessor :stack def initialize @stack = [] end def add(el) stack << el end def remove stack.pop end def show puts stack end end class Queue attr_accessor :stack def initialize @stack = [] end def enqueue(el) stack << el end def dequeue stack.shift end def show puts stack end end class Map attr_accessor :map def initialize @map = {} end def assign(key, val) map[key] = val end def lookup(key) map[key] end def remove(key) map.delete(key) end def show puts map end end
require_relative "dish.rb" class Order def initialize (dish_list = [], total_price = 0.0) @dish_list = dish_list @total_price = 0.0 end def dish_list @dish_list end def add(dish) dish_list << dish end def total_price @total_price = dish_list.inject(0) {|total, dish| total + dish.price} end def dish_quantity_of_type(dish_type) dish_quantity = 0 dish_list.each { |dish| dish_quantity += 1 if dish.type == dish_type} dish_quantity end def price_for_dish_quantity_of_type(dish_type) dish_quantity_price = 0.0 selected_type = [] selected_type = dish_list.select {|dish| dish.type == dish_type} if !selected_type.empty? dish_quantity_price = (dish_quantity_of_type(dish_type) * selected_type[0].price) end dish_quantity_price end end
require 'spec_helper' describe 'mysql::server' do on_pe_supported_platforms(PLATFORMS).each do |pe_version,pe_platforms| pe_platforms.each do |pe_platform,facts| describe "on #{pe_version} #{pe_platform}" do let(:facts) { facts } context 'with defaults' do it { is_expected.to contain_class('mysql::server::install') } it { is_expected.to contain_class('mysql::server::config') } it { is_expected.to contain_class('mysql::server::service') } it { is_expected.to contain_class('mysql::server::root_password') } it { is_expected.to contain_class('mysql::server::providers') } end # make sure that overriding the mysqld settings keeps the defaults for everything else context 'with overrides' do let(:params) {{ :override_options => { 'mysqld' => { 'socket' => '/var/lib/mysql/mysql.sock' } } }} it do is_expected.to contain_file('mysql-config-file').with({ :mode => '0644', }).with_content(/basedir/) end end describe 'with multiple instance of an option' do let(:params) {{ :override_options => { 'mysqld' => { 'replicate-do-db' => ['base1', 'base2', 'base3'], } }}} it do is_expected.to contain_file('mysql-config-file').with_content( /^replicate-do-db = base1$/ ).with_content( /^replicate-do-db = base2$/ ).with_content( /^replicate-do-db = base3$/ ) end end describe 'an option set to true' do let(:params) { { :override_options => { 'mysqld' => { 'ssl' => true } }} } it do is_expected.to contain_file('mysql-config-file').with_content(/^\s*ssl\s*(?:$|= true)/m) end end describe 'an option set to false' do let(:params) { { :override_options => { 'mysqld' => { 'ssl' => false } }} } it do is_expected.to contain_file('mysql-config-file').with_content(/^\s*ssl = false/m) end end context 'with remove_default_accounts set' do let (:params) {{ :remove_default_accounts => true }} it { is_expected.to contain_class('mysql::server::account_security') } end describe 'possibility of disabling ssl completely' do let(:params) { { :override_options => { 'mysqld' => { 'ssl' => true, 'ssl-disable' => true } }} } it do is_expected.to contain_file('mysql-config-file').without_content(/^\s*ssl\s*(?:$|= true)/m) end end context 'mysql::server::install' do let(:params) {{ :package_ensure => 'present', :name => 'mysql-server' }} it do is_expected.to contain_package('mysql-server').with({ :ensure => :present, :name => 'mysql-server', }) end end if pe_platform =~ /redhat-7/ context 'mysql::server::install on RHEL 7' do let(:params) {{ :package_ensure => 'present', :name => 'mariadb-server' }} it do is_expected.to contain_package('mysql-server').with({ :ensure => :present, :name => 'mariadb-server', }) end end end context 'mysql::server::config' do context 'with includedir' do let(:params) {{ :includedir => '/etc/my.cnf.d' }} it do is_expected.to contain_file('/etc/my.cnf.d').with({ :ensure => :directory, :mode => '0755', }) end it do is_expected.to contain_file('mysql-config-file').with({ :mode => '0644', }) end it do is_expected.to contain_file('mysql-config-file').with_content(/!includedir/) end end context 'without includedir' do let(:params) {{ :includedir => '' }} it do is_expected.not_to contain_file('mysql-config-file').with({ :ensure => :directory, :mode => '0755', }) end it do is_expected.to contain_file('mysql-config-file').with({ :mode => '0644', }) end it do is_expected.to contain_file('mysql-config-file').without_content(/!includedir/) end end end context 'mysql::server::service' do context 'with defaults' do it { is_expected.to contain_service('mysqld') } end context 'service_enabled set to false' do let(:params) {{ :service_enabled => false }} it do is_expected.to contain_service('mysqld').with({ :ensure => :stopped }) end end end context 'mysql::server::root_password' do describe 'when defaults' do it { is_expected.not_to contain_mysql_user('root@localhost') } it { is_expected.not_to contain_file('/root/.my.cnf') } end describe 'when set' do let(:params) {{:root_password => 'SET' }} it { is_expected.to contain_mysql_user('root@localhost') } it { is_expected.to contain_file('/root/.my.cnf') } end end context 'mysql::server::providers' do describe 'with users' do let(:params) {{:users => { 'foo@localhost' => { 'max_connections_per_hour' => '1', 'max_queries_per_hour' => '2', 'max_updates_per_hour' => '3', 'max_user_connections' => '4', 'password_hash' => '*F3A2A51A9B0F2BE2468926B4132313728C250DBF' }, 'foo2@localhost' => {} }}} it { is_expected.to contain_mysql_user('foo@localhost').with( :max_connections_per_hour => '1', :max_queries_per_hour => '2', :max_updates_per_hour => '3', :max_user_connections => '4', :password_hash => '*F3A2A51A9B0F2BE2468926B4132313728C250DBF' )} it { is_expected.to contain_mysql_user('foo2@localhost').with( :max_connections_per_hour => nil, :max_queries_per_hour => nil, :max_updates_per_hour => nil, :max_user_connections => nil, :password_hash => '' )} end describe 'with grants' do let(:params) {{:grants => { 'foo@localhost/somedb.*' => { 'user' => 'foo@localhost', 'table' => 'somedb.*', 'privileges' => ["SELECT", "UPDATE"], 'options' => ["GRANT"], }, 'foo2@localhost/*.*' => { 'user' => 'foo2@localhost', 'table' => '*.*', 'privileges' => ["SELECT"], }, }}} it { is_expected.to contain_mysql_grant('foo@localhost/somedb.*').with( :user => 'foo@localhost', :table => 'somedb.*', :privileges => ["SELECT", "UPDATE"], :options => ["GRANT"] )} it { is_expected.to contain_mysql_grant('foo2@localhost/*.*').with( :user => 'foo2@localhost', :table => '*.*', :privileges => ["SELECT"], :options => nil )} end describe 'with databases' do let(:params) {{:databases => { 'somedb' => { 'charset' => 'latin1', 'collate' => 'latin1', }, 'somedb2' => {} }}} it { is_expected.to contain_mysql_database('somedb').with( :charset => 'latin1', :collate => 'latin1' )} it { is_expected.to contain_mysql_database('somedb2')} end end end end end end
JSONAPI.configure do |config| # custom processor for nested models config.default_processor_klass = Api::V1::BaseProcessor config.json_key_format = :underscored_key config.route_format = :underscored_key # config.resource_cache = Rails.cache config.allow_include = true config.allow_sort = true config.allow_filter = true config.top_level_meta_include_record_count = true config.top_level_meta_record_count_key = :record_count # config.default_paginator = :paged # config.default_page_size = 10 # config.maximum_page_size = 100 # config.top_level_meta_include_page_count = true # config.top_level_meta_page_count_key = :page_count config.exception_class_whitelist = [ActiveRecord::RecordInvalid] end # monkey patch for translation of attributes in error messages JSONAPI::Exceptions::ValidationErrors.class_eval do def format_key(key) I18n.t("api.attributes.#{key}", default: @key_formatter.format(key)) end end # monkey patch for nested models in relationships JSONAPI::RequestParser.class_eval do def parse_to_one_relationship(link_value, relationship) if link_value.nil? || link_value[:data].blank? linkage = nil else linkage = link_value[:data] end links_object = parse_to_one_links_object(linkage) if !relationship.polymorphic? && links_object[:type] && (links_object[:type].to_s != relationship.type.to_s) fail JSONAPI::Exceptions::TypeMismatch.new(links_object[:type]) end unless links_object[:id].nil? resource = self.resource_klass || Resource relationship_resource = resource.resource_for(unformat_key(links_object[:type]).to_s) relationship_id = relationship_resource.verify_key(links_object[:id], @context) if relationship.polymorphic? { id: relationship_id, type: unformat_key(links_object[:type].to_s) } else relationship_id end else nil end end def parse_to_one_links_object(raw) if raw.nil? return { type: nil, id: nil } end if !(raw.is_a?(Hash) || raw.is_a?(ActionController::Parameters)) # || # raw.keys.length != 2 || !(raw.key?('type') && raw.key?('id')) fail JSONAPI::Exceptions::InvalidLinksObject.new end # { # type: unformat_key(raw['type']).to_s, # id: raw['id'] # } raw.merge( type: unformat_key(raw['type']).to_s ). to_unsafe_h. # TODO: Permit the params and use to_h deep_symbolize_keys end def parse_to_many_links_object(raw) fail JSONAPI::Exceptions::InvalidLinksObject.new if raw.nil? links_object = {} if raw.is_a?(Array) raw.each do |link| link_object = parse_to_one_links_object(link) links_object[link_object[:type]] ||= [] links_object[link_object[:type]].push(link_object)#[:id]) end else fail JSONAPI::Exceptions::InvalidLinksObject.new end links_object end end
class CreateLocationRoutes < ActiveRecord::Migration def change create_table :location_routes do |t| t.integer :start_id t.integer :end_id t.integer :distance t.string :polyline end add_index :location_routes, [:start_id, :end_id], :unique => true end end
# # # # class HumanPlayer def initialize @code = [0,0,0,0] end def get_code valid = false while !valid print "Enter code of 4 space-separated numbers between 1-6: " code = STDIN.gets.chomp valid = validate?(code) if !valid puts "Please enter 4 space-separated numbers between 1-6, try again..." end end @code.map(&:to_i) end def get_next_guess(current_clue_array, current_guess_array) valid = false while !valid print "Enter guess of 4 space-separated numbers between 1-6: " guess = STDIN.gets.chomp valid = validate?(guess) if !valid puts "Please enter 4 space-separated numbers between 1-6, try again..." end end @code end private def validate?(code_str) retval = true @code = code_str.split(' ') if @code.length != 4 retval = false end @code.each {|el| if el.to_i < 1 || el.to_i > 6 retval = false end } retval end end
# frozen_string_literal: true require "rails_helper" RSpec.describe CollectionPoint, type: :model do subject(:collection_point) { create(:collection_point, coordinator: coordinator) } let!(:address) { create(:address, addressable: collection_point) } let!(:coordinator) { create(:user) } describe "#address" do it "has one address" do expect(collection_point.address).to eq(address) end end describe "#coordinator" do it "has one coordinator" do expect(collection_point.coordinator).to eq(coordinator) end it "must have a coordinator" do expect { collection_point.update!(coordinator: nil) }.to raise_error(ActiveRecord::RecordInvalid) end end end
require "etc" require "fileutils" require "find" require "mail" require "socket" require "date" require "permCheck/version" require "modeBits" # Check permissons and group ownership of files. # # @author Gord Brown module PermCheck # Top-level class to carry out an audit. class PermCheck # Set up for audit. def initialize(umask,smask,group) @umask = ModeBits.txt2num(umask) @smask = ModeBits.txt2num(smask) @group = group @gid = Etc.getgrnam(group).gid @messages = [] end # Run the audit. def audit(root) count = 0 Find.find(root) do |path| bad = false if File.symlink?(path) lstat = File.lstat(path) # check group ownership of link (not target) # note we don't check permissions, or existence of target, # because permissions are irrelevant for symlinks, and # we don't care if those symlinks are broken. (Somebody # else can care about that.) if lstat.gid != @gid gp = Etc.getgrgid(lstat.gid) pwent = Etc.getpwuid(lstat.uid) @messages << "group #{gp.name} != #{@group}: path '#{path}' (#{pwent.name})" bad = true end else stat = File.stat(path) if !File.readable?(path) pwent = Etc.getpwuid(stat.uid) @messages << "unreadable: path '#{path}' (#{pwent.name})" bad = true else if stat.gid != @gid gp = Etc.getgrgid(stat.gid) pwent = Etc.getpwuid(stat.uid) @messages << "group #{gp.name} != #{@group}: path '#{path}' (#{pwent.name})" bad = true end if (stat.mode&@umask != 0) || (stat.mode&@smask == 0) modestr = ModeBits.num2txt(stat.mode) pwent = Etc.getpwuid(stat.uid) @messages << "mode violation #{modestr}: path '#{path}' (#{pwent.name})" bad = true end end end if bad count += 1 Find.prune end end return count end # Report on the audit. def report(mailto) text = formatMsg() if mailto.nil? STDOUT.puts(text) else targets = mailto.split(",") Mail.deliver do from "permissionsAudit@#{Socket.gethostname}" to targets subject "file permissions check" body text end end end def formatMsg() host = Socket.gethostname runningAt = Time.now.strftime("%Y-%b-%d %H:%M") strs = ["Permissions check: #{host} at #{runningAt}\n"] strs << "umask: #{ModeBits.num2txt(@umask)}" strs << "smask: #{ModeBits.num2txt(@smask)}" strs << "group: #{@group}\n" strs << "MESSAGES:" @messages.sort! @messages.each do |m| strs << m end return strs.join("\n") end end end
class Favour < ApplicationRecord CATEGORY = %w[Groceries Gardening Pets Pharmacy Chat Other] STATUS = %w[Open Accepted Done Expired Deleted] # Geocoded geocoded_by :address # Associations belongs_to :recipient, :class_name => 'User', optional: true belongs_to :helper, :class_name => 'User', optional: true has_many :reviews has_many :favour_applications # Validations validates :category, presence: true validates :title, presence: true validates :description, presence: true validates :address, presence: true validates :completion_asap, presence: true validates :completion_date, presence: true, unless: -> { :completion_asap } after_validation :geocode, if: :will_save_change_to_address? # Simple form collections def self.categories CATEGORY end def accepted self.favour_applications.each do |app| app.status == "Rejected" unless app.status == "Accepted" end self.status = "Accepted" end def applicants_applied? applications = self.favour_applications.where(status: "Pending") || self.favour_applications.where(status: "Accepted") applications.length > 0 ? true : false end end
class Category < ApplicationRecord has_many :work_categories has_many :works, through: :work_categories validates :name, presence: true, length: {minimum: 3, maximum: 25 } validates_uniqueness_of :name end
class DisplayReportContext < BaseContext attr_accessor :audit_report, :report_template, :for_pdf, :user def initialize(*) super raise 'audit_report' unless audit_report self.for_pdf = false if @for_pdf.nil? end def as_json { form_html: form_html, display_report: display_report_as_json, preview_url: preview_report_url } end def display_report_for_form DisplayReportBuilder.new( audit_report: audit_report, audit_report_calculator: audit_report_calculator, contentblock_mode: 'active', default_markdown: '', markdown_source: report_template ).display_report end memoize :display_report_for_form def display_report_for_preview DisplayReportBuilder.new( audit_report: audit_report, audit_report_calculator: audit_report_calculator, contentblock_mode: 'rendered', default_markdown: '', for_pdf: for_pdf, markdown_source: report_template ).display_report end memoize :display_report_for_preview def filename audit_report.name end def form_html display_report_for_form.formatted_report end def layout report_template.layout end def pdf_options { pdf: filename, page_size: 'Letter', layout: 'calc/layouts/pdf.html.erb', template: "calc/layouts/pdf/#{layout}/body.html.erb", disable_smart_shrinking: true, locals: { context: self }, margin: { top: 10, bottom: 10, left: 10, right: 10 }, header: { html: { locals: { context: self }, template: "calc/layouts/pdf/#{layout}/header.html.erb" } }, footer: { locals: { report: audit_report }, html: { locals: { context: self }, template: "calc/layouts/pdf/#{layout}/footer.html.erb" } }, disposition: 'inline' } end def pdf_path url_helpers.calc_audit_report_display_path(audit_report) end def preview_html display_report_for_preview.formatted_report end def report AuditReportPresenter.new(audit_report) end memoize :report private def audit_report_calculator AuditReportCalculator.new( audit_report: audit_report) end memoize :audit_report_calculator def display_report_as_json DisplayReportSerializer.new( audit_report: audit_report, display_report: display_report_for_preview).as_json end def preview_report_url url_helpers.preview_calc_audit_report_display_path(audit_report) end end
require "test_helper" class IngestersControllerTest < ActionDispatch::IntegrationTest setup do @ingester = ingesters(:one) end test "should get index" do get ingesters_url assert_response :success end test "should get new" do get new_ingester_url assert_response :success end test "should create ingester" do assert_difference('Ingester.count') do post ingesters_url, params: { ingester: { } } end assert_redirected_to ingester_url(Ingester.last) end test "should show ingester" do get ingester_url(@ingester) assert_response :success end test "should get edit" do get edit_ingester_url(@ingester) assert_response :success end test "should update ingester" do patch ingester_url(@ingester), params: { ingester: { } } assert_redirected_to ingester_url(@ingester) end test "should destroy ingester" do assert_difference('Ingester.count', -1) do delete ingester_url(@ingester) end assert_redirected_to ingesters_url end end
class AddInprogressToIssues < ActiveRecord::Migration[5.1] def change add_column :issues, :inprogress, :datetime, null: true add_column :issues, :released, :datetime, null: true end end
class Page < ActiveRecord::Base #How to provide a foreign_key #belongs_to :subject, {foreign_key: "subject_id"} belongs_to :subject has_many :sections end
# encoding: utf-8 class Liquidacion < ActiveRecord::Base before_save :salvar_calculados before_save :set_saldo # Relacion con carpeta, cliente, personal, doc belongs_to :carpeta belongs_to :cliente belongs_to :personal belongs_to :documento has_many :pagos # Valida la precensia de los campos validates_presence_of :fob_dolares, :seguro, :flete_I, :almacenaje, :gastos_tramite, :nuestros_servicios, :descripcion, :fecha # Realiza calculos de liquidacion, sumas def salvar_calculados self.cif_dolares = fob_dolares.to_f + seguro.to_f + flete_I.to_f + flete_II.to_f + otros_gastos.to_f self.cif_bolivianos = 7.07 * cif_dolares.to_f self.ga = cif_bolivianos * 0.10 self.iva = (cif_bolivianos.to_f + ga.to_f) * 0.1494 self.ice = (cif_bolivianos.to_f + ga.to_f) * 0.18 self.total_impuestos = ga.to_f + iva.to_f + ice.to_f + diu.to_f # otros_1 = ibmetro # otros_2 = ibnorca self.total_servicios = almacenaje.to_f + senasac.to_f + camara_comercio.to_f + otros_1.to_f + otros_2.to_f + nuestros_servicios.to_f + gastos_tramite.to_f self.total_despacho = total_impuestos.to_f + total_servicios.to_f end def set_saldo if self.saldo.nil? self.saldo = total_despacho.to_f end end end
class CreateRetrospective < ActiveRecord::Migration def change create_table :retrospectives do |t| t.integer :number t.references :sprint, index: true, foreign_key: true t.references :project, index: true, foreign_key: true end end end
class Price < ActiveRecord::Base belongs_to :menu_item belongs_to :price_title belongs_to :item_type_variant def self.find_by_menu(menu_id) sql = "SELECT p.* FROM menu_items mi " + "JOIN prices p ON mi.id = p.menu_item_id " + "WHERE mi.menu_id = ?" Price.find_by_sql [sql, menu_id] end end
require 'rails_helper' RSpec.describe "Quiz", type: :request do let!(:question) { create(:question) } let!(:questions) { [question] + create_list(:question, 5) } describe 'GET /quiz' do before { get quiz_index_path } it 'succeeds' do expect(response).to be_success end it 'outputs a list of all question titles' do questions.each do |question| expect(response.body).to include(question.title) end end end describe 'GET /quiz/1' do before { get quiz_path(question) } it 'succeeds' do expect(response).to be_success end it 'outputs the question' do expect(response.body).to include(question.body) end it 'does not output the answer' do expect(response.body).not_to include(question.answer) end it 'outputs a form that allows the user to answer' do path = Regexp.escape(answer_quiz_path(question)) expect(response.body).to match(/<form [^>]*action=\"#{path}\"/) end end describe 'GET /quiz/random' do before do expect(Question).to receive(:random) { question } get random_quiz_index_path end it 'succeeds' do expect(response).to be_success end it 'outputs the question' do expect(response.body).to include(question.body) end it 'does not output the answer' do expect(response.body).not_to include(question.answer) end it 'outputs a form that allows the user to answer' do path = Regexp.escape(answer_quiz_path(question)) expect(response.body).to match(/<form [^>]*action=\"#{path}\"/) end end describe 'GET /quiz/1/answer' do context 'when no answer is supplied' do it 'fails with a 400 error' do expect { get answer_quiz_path(question) }.to raise_error(ActionController::ParameterMissing) end end context 'when an answer is supplied' do before { get answer_quiz_path(question), params: { answer: answer } } context 'and is empty' do let(:answer) { '' } it 'redirects the user to the quiz, and asks to supply an answer' do expect(response).to redirect_to(quiz_path(question)) follow_redirect! expect(response.body).to include('You need to submit an answer.') end end context 'and is incorrect' do let(:answer) { 'incorrect' } it 'redirects the user to the quiz, and tells answer was incorrect' do expect(response).to redirect_to(quiz_path(question)) follow_redirect! expect(response.body).to include('Your answer is incorrect!') end end context 'and is correct' do let(:answer) { question.answer } it 'succeeds' do expect(response).to be_success end it 'tells the user their answer was correct' do expect(response.body).to include('Correct') end end end end end
module OnboardDatax class OnboardSearchStatConfig < ActiveRecord::Base attr_accessor :config_desp, :brief_note, :engine_name, :labels_and_fields, :resource_name, :search_list_form, :search_params, :search_results_period_limit, :search_summary_function, :search_where, :stat_function, :stat_header, :stat_summary_function, :time_frame, :last_updated_by_name, :project_name attr_accessible :project_id, :search_stat_config_id, :custom_stat_header, :custom_search_summary_function, :custom_stat_summary_function, :engine_id, :engine_name, :project_name, :brief_note, :config_desp, :engine_id, :labels_and_fields, :resource_name, :search_list_form, :search_params, :search_results_period_limit, :search_summary_function, :search_where, :stat_function, :stat_header, :stat_summary_function, :time_frame, :project_name, :as => :role_new attr_accessible :last_updated_by_name, :custom_stat_header, :custom_search_summary_function, :brief_note, :config_desp, :engine_id, :labels_and_fields, :resource_name, :search_list_form, :search_params, :search_results_period_limit, :search_summary_function, :search_where, :stat_function, :stat_header, :stat_summary_function, :time_frame, :custom_stat_summary_function, :engine_name, :project_name, :as => :role_update attr_accessor :start_date_s, :end_date_s, :resource_name_s, :engine_name_s, :config_desp_s, :project_id_s attr_accessible :start_date_s, :end_date_s, :resource_name_s, :engine_name_s, :config_desp_s, :project_id_s, :as => :role_search_stats belongs_to :last_updated_by, :class_name => 'Authentify::User' belongs_to :search_stat_config, :class_name => OnboardDatax.search_stat_config_class.to_s belongs_to :project, :class_name => OnboardDatax.project_class.to_s belongs_to :engine, :class_name => OnboardDatax.engine_class.to_s validates :project_id, :search_stat_config_id, :engine_id, :presence => true, :numericality => {:only_integer => true, :greater_than => 0} validates :search_stat_config_id, :uniqueness => {:scope => :project_id, :case_sensitive => false, :message => I18n.t('Duplicate Search/Stat Config')} #cnovert to csv def self.to_csv CSV.generate do |csv| #header array header = ['id', 'resource_name', 'stat_function', 'stat_summary_function', 'labels_and_fields', 'time_frame', 'search_list_form', 'search_where', 'search_results_period_limit', 'last_updated_by_id', 'brief_note', 'created_at', 'updated_at', 'stat_header', 'search_params', 'search_summary_function'] csv << header all.each do |config| #assembly array for the row base = OnboardDatax.search_stat_config_class.find_by_id(config.attributes.values_at('search_stat_config_id')[0].to_i) row = Array.new row << config.attributes.values_at('id')[0] row << base.stat_function row << (config.attributes.values_at('custom_stat_summary_function')[0].present? ? config.attributes_values_at('custom_stat_summary_function')[0] : base.stat_summary_function) row << base.labels_and_fields row << base.time_frame row << base.search_list_form row << base.search_where row << base.search_results_period_limit row << config.attributes.values_at('last_updated_by_id')[0] row << base.brief_note row << config.attributes.values_at('created_at')[0] row << config.attributes.values_at('updated_at')[0] row << (config.attributes.values_at('custom_stat_header')[0].present? ? config.attributes_values_at('custom_stat_header')[0] : base.stat_header) row << base.search_params row << (config.attributes.values_at('custom_search_summary_function')[0].present? ? config.attributes_values_at('custom_search_summary_function')[0] : base.search_summary_function) #inject to csv csv << row end end end end end
# ruby ~/Dropbox/Projects/ruby/ruby-snippet-examples/hash_array_looping.rb # Hash https://ruby-doc.org/core-2.5.1/Hash.html grades = { "Jane Doe" => 10, "Jim Doe" => 6 } p grades # to access puts grades["Jim Doe"] # alternate syntax for eys that are symbols options = { :font_size => 10, :font_family => "Arial" } # could also be written as: options = { font_size: 10, font_family: "Arial" } p options # To access puts options[:font_size] # Hashes can also be created using the new method grades = Hash.new grades["Dorothy Doe"] = 9 p grades # Hashes are an easy way to represent data structures books = {} books[:matz] = "The Ruby Programming Language" books[:black] = "The Well-Grounded Rubyist" p books puts "------------------------------------------------" # ----- HASH LOOPING ----- business = { "name" => "Treehouse", "location" => "Portland, OR" } business.each do |key, value| puts "The hash key is #{key} and the value is #{value}." end # Iterate over keys only business.each_key do |key| puts "Key: #{key}" end # Iterate over values only business.each_value do |value| puts "Value: #{value}" end puts "------------------------------------------------" ## More complex example cars = {} # cars["volvo"] = {name: "Volvo", stock: 22, sold: 18} # cars["bmw"] = {name: "BMW", stock: 15, sold: 13} # cars["saab"] = {name: "SAAB", stock: 5, sold: 2} # cars["land_rover"] = {name: "Land Rover", stock: 17, sold: 15} cars = { "volvo" => { name: "Volvo", stock: 22, sold: 18 }, "bmw" => { name: "BMW", stock: 15, sold: 13 }, "saab" => { name: "SAAB", stock: 5, sold: 2 }, "land_rover" => { name: "Land Rover", stock: 17, sold: 15 } } p cars cars.each do |key, value| puts "The hash key is #{key} and the value is #{value}." end cars.each do |key, values| puts "the key is #{key}" values.each do |k, v| puts "the value key is ** #{k} ** and each value is ** #{v} **" end end puts "\n------------------------------------------------\n" # get only unique values from a multi-di hash FILTER_TYPES = { text: [ {text: "contains", value: "cont"}, {text: "does not contain", value: "not_cont"}, {text: "is", value: "cont_all"}, {text: "is not", value: "not_cont_all"}, {text: "begins with", value: "start"}, {text: "ends with", value: "end"}, {text: "in", value: "in"} ], date: [ {text: "is", value: "cont_all"}, {text: "is not", value: "not_cont_all"}, #{text: "is after", value: ""}, #{text: "is before", value: ""}, # {text: "in the last", value: ""} # this will need an additional filter (days, months, years) # {text: "not in the last", value: ""} # this will need an additional filter (days, months, years) #"is in the range" # (note this will need to add an additional filter input field) ], int: [ {text: "is", value: "cont_all"}, {text: "is not", value: "not_cont_all"}, {text: "is greater than", value: "gt"}, {text: "is less than", value: "lt"} #"is in the range" // (note this will need to add an additional filter input field) ], bool: [ {text: "is true", value: "true"}, {text: "is false", value: "false"}, {text: "is blank", value: "blank"} ] } #puts FILTER_TYPES.collect{|k,v| puts v} #p FILTER_TYPES.reverse.map{|x| x[0]} #p FILTER_TYPES.map.with_object({}) {|k,v| v[k[0]] = k }.values FILTER_TYPES.map.with_object({}) do |k,v| #p k[k[0]] #p v[] end #p FILTER_TYPES[:text].flatten FILTER_TYPES.each_with_index do |k,v| p FILTER_TYPES[k[v]] end all_filters = [] FILTER_TYPES.each do |key,value| value.each do |k, v| all_filters.push(k[:value]) end end p all_filters.uniq!
class Invoice < ActiveRecord::Base include ActionView::Helpers::NumberHelper belongs_to :delivery has_many :invoice_items, :dependent => :destroy has_many :items, :through => :invoice_items attr_accessible :invoice_number, :fob_total_cost, :total_units, :delivery_id, :user_id validate :invoice_number, :presence => true, :uniqueness => true def item_ids self.invoice_items.map {|x| x.item_id} end end
require_relative "../../../lib/google_mail" require_relative "../../../lib/eapol_test" feature "Signup" do include_context "signup" it "signs up successfully" do gmail = GoogleMail.new test_email = gmail.account_email.gsub(/@/, "+#{Time.now.to_i}@") gmail.send_email( "signup@wifi.service.gov.uk", test_email, "", "", ) body = nil Timeout.timeout(20, nil, "Waited too long for signup email") do loop do if (message = gmail.read("is:unread to:#{test_email}")) body = message&.payload&.parts&.first&.body&.data break end print "." sleep 1 end end identity = body.scan(/Your username: ([a-z]{6})/)&.first&.first password = body.scan(/Your password: ((?:[A-Z][a-z]+){3})/)&.first&.first expect(identity).to be expect(password).to be time_now = Time.now radius_server_reboot_scheduled = time_now.between?( Time.new(time_now.year, time_now.month, time_now.day, 1, 0, 0), Time.new(time_now.year, time_now.month, time_now.day, 1, 15, 0), ) unless radius_server_reboot_scheduled radius_ips = ENV["RADIUS_IPS"].split(",") radius_ips_successful = EapolTest.make_test(ssid: "GovWifi", identity: identity, password: password) do |eapol_test| radius_ips.select do |radius_ip| eapol_test.execute(ENV["RADIUS_KEY"], radius_ip) end end expect(radius_ips_successful).to eq radius_ips end end end
# -*- mode: ruby -*- # vi: set ft=ruby : # wit home Enterprise virtual (KVM) servers: # 1. Proxy (forward and reverse) # 2. Extranet web server (wiki) Vagrant.configure("2") do |config| config.vm.box = "centos/7" config.vm.synced_folder "./", "/vagrant", type: "nfs" config.vm.provider :libvirt do |libvirt,override| libvirt.host = "192.168.1.12" libvirt.connect_via_ssh = true libvirt.username = "aylingw" #libvirt.password - leave blank, because using SSH to login with private key #libvirt.id_ssh_key_file - leave blank which assumes the default ${HOME}/.ssh/id_rsa libvirt.cpus = 1 libvirt.memory = 1024 libvirt.autostart = true #libvirt.mgmt_attach = false end config.vm.define :proxy do |proxy| proxy.vm.hostname = "proxy.wozitech.local" proxy.vm.network :private_network, libvirt__network_name: "DMZ" proxy.vm.provider :libvirt do |domain| end proxy.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/hosts/proxy/proxy.yml" ansible.compatibility_mode = "2.0" ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS'] end proxy.vm.post_up_message = "The proxy server is up and running" end config.vm.define :web1 do |web| web.vm.hostname = "web1.wozitech.local" web.vm.network :private_network, libvirt__network_name: "DMZ" web.vm.provider :libvirt do |domain| end web.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/hosts/extranet/extranet.yml" ansible.compatibility_mode = "2.0" ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS'] end web.vm.post_up_message = "The Extranet web server is up and running" end config.vm.define :web2 do |web2| web2.vm.hostname = "web2.wozitech.local" web2.vm.network :private_network, libvirt__network_name: "DMZ" web2.vm.provider :libvirt do |domain| domain.memory = 8192 end web2.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/hosts/web2/web2.yml" ansible.compatibility_mode = "2.0" ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS'] end web2.vm.post_up_message = "The Extranet web server is up and running" end config.vm.define :nexus do |nexus| nexus.vm.hostname = "nexus.wozitech.local" nexus.vm.network :private_network, libvirt__network_name: "DMZ" nexus.vm.provider :libvirt do |domain| domain.memory = 2048 domain.storage :file, :size => "40G", :type => "qcow2" end nexus.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/hosts/nexus/nexus.yml" ansible.compatibility_mode = "2.0" ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS'] end nexus.vm.post_up_message = "The nexus server is up and running" end config.vm.define :vault do |vault| vault.vm.hostname = "vault.wozitech.local" vault.vm.network :private_network, libvirt__network_name: "DMZ" vault.vm.provider :libvirt do |domain| end vault.vm.provision "ansible" do |ansible| ansible.playbook = "ansible/hosts/vault/vault.yml" ansible.compatibility_mode = "2.0" ansible.raw_arguments = Shellwords.shellsplit(ENV['ANSIBLE_ARGS']) if ENV['ANSIBLE_ARGS'] end vault.vm.post_up_message = "The Hashicorp Vault server is up and running" end end
# # myapp.rb # ConstantContact # # Copyright (c) 2013 Constant Contact. All rights reserved. require 'rubygems' require 'sinatra' require 'active_support' require 'yaml' require 'constantcontact' # This is a Sinatra application (http://www.sinatrarb.com/). # Update config.yml with your data before running the application. # Run this application like this : ruby myapp.rb # Name this action according to your # Constant Contact API Redirect URL, see config.yml get '/cc_callback' do cnf = YAML::load(File.open('config/config.yml')) @oauth = ConstantContact::Auth::OAuth2.new( :api_key => cnf['api_key'], :api_secret => cnf['api_secret'], :redirect_url => cnf['redirect_url'] ) @error = params[:error] @user = params[:username] @code = params[:code] if @code begin @lists = [] response = @oauth.get_access_token(@code) @token = response['access_token'] cc = ConstantContact::Api.new(cnf['api_key'], @token) lists = cc.get_lists() if lists lists.each do |list| # Select the first list, by default selected = list == lists.first @lists << { 'id' => list.id, 'name' => list.name, 'selected' => selected } end end rescue => e message = parse_exception(e) @error = "An error occured when saving the contacts : " + message end erb :contacts_multipart else erb :callback end end # Name this action according to your # Constant Contact API Redirect URL, see config.yml post '/cc_callback' do cnf = YAML::load(File.open('config/config.yml')) @error = params[:error] @user = params[:username] @code = params[:code] @token = params[:token] if @code cc = ConstantContact::Api.new(cnf['api_key'], @token) @activity = params[:activity] lists = params[:lists] || {} lists['checkboxes'] = [] if lists['checkboxes'].blank? @lists = [] if lists['ids'] lists['ids'].each do |key, list_id| list_name = lists['names'][key] selected = !(lists['checkboxes'].blank? || lists['checkboxes'][key].blank?) @lists << { 'id' => list_id, 'name' => list_name, 'selected' => selected } end end begin if @activity # Validate raise 'Please select a file' if @activity['file'].blank? file_name = @activity['file'][:filename] contents = @activity['file'][:tempfile].read add_to_lists = [] lists['ids'].each do |key, list_id| add_to_lists << list_id if lists['checkboxes'][key] end add_to_lists = add_to_lists.join(',') if /remove_contacts/.match(file_name) cc.add_remove_contacts_from_lists_activity_from_file(file_name, contents, add_to_lists) elsif /add_contacts/.match(file_name) cc.add_create_contacts_activity_from_file(file_name, contents, add_to_lists) end redirect '/cc_callback' end rescue => e message = parse_exception(e) @error = "An error occured when saving the contacts : " + message #puts e.backtrace end erb :contacts_multipart else erb :callback end end def parse_exception(e) if e.respond_to?(:response) hash_error = JSON.parse(e.response) message = hash_error.first['error_message'] else message = e.message end message.to_s end
name1 = "Joe" name2 = "Needa" puts "Hello %s, where is %s?" %[name1, name2] #Another way of putting variables inside a string is called "string interpolation" which uses #{} (pound and curly bracket). The next 3 lines will demonstrate this: name1 = "Joe" name2 = "Needa" puts "Hello #{name1}, where is #{name2}?" #below are examples of cryptic variable names. x = "There are #{10} types of people." binary = "binary" do_not = "don't" y = "Those who know #{binary} and those who #{do_not}." #2 puts x puts y puts "I said: #{x}." #2 puts "I also said: '#{y}'." #3 hilarious = false joke_evaluation = "Isn't that joke so funny?! #{hilarious}" #4 puts joke_evaluation w = "This is the left side of..." e = "a string with a right side." puts w + e #The reason why this makes a long string is because we are adding w with e by inserting + between the two variables after assigning the strings.
module Fog module Hetznercloud class Compute class Real def floating_ip_update_dns_ptr(id, body) create("/floating_ips/#{id}/actions/change_dns_ptr", body) end end class Mock def floating_ip_update_dns_ptr(_type, _body) Fog::Mock.not_implemented end end end end end
class Board < ActiveRecord::Base belongs_to :user has_many :pins validates :name, :presence => true end
class CreateEntries < ActiveRecord::Migration def change create_table :entries do |t| t.datetime :start t.datetime :stop t.string :project t.string :description t.boolean :open? t.time :elapsed t.timestamps null: false end end end
class ProgressBar module Components class Throttle include Timer def initialize options = {} @period = options.delete :throttle_period end def choke force=false, &block if not started? or not @period or force or elapsed >= @period yield start end end private def elapsed now - @started_at end end end end
class Animal attr_reader :diet def initialize(diet, superpower) @diet = diet @superpower = superpower end def move puts "I'm moving!" end def superpower puts "I can #{@superpower}!" end end class Fish < Animal def move puts "I'm swimming!" end end class Bird < Animal end class FlightlessBird < Bird def initialize(diet, superpower) super end def move puts "I'm running!" end end class SongBird < Bird def initialize(diet, superpower, song) super(diet, superpower) # Added <(diet, superpower)> as a solution ##! If you don't specify, the # of arguments to send to super, it will send # all of them from the initialize of the class that inherits. # It will send diet, superpower, and song to <Animal> class here if you only # have <super>, hence the original error of sending three arguments instead of 2 @song = song end def move puts "I'm flying!" end end # Examples unicornfish = Fish.new(:herbivore, 'breathe underwater') unicornfish.superpower unicornfish.move p unicornfish.diet penguin = FlightlessBird.new(:carnivore, 'drink sea water') robin = SongBird.new(:omnivore, 'sing', 'chirp chirrr chirp chirp chirrrr') p robin.diet robin.superpower robin.move
module ApplicationHelper def resource_name :user end def resource @resource ||= User.new end def devise_mapping @devise_mapping ||= Devise.mappings[:user] end def user_avatar user, style, css_class = "" if user.profile image_tag user.profile.avatar.url(style), class: "img-circle #{css_class}" else image_tag "/images/#{style.to_s}/missing.jpeg", class: "img-circle #{css_class}" end end end
module MalauzaiPlaces class Client attr_reader :api_key attr_reader :options def initialize(api_key = @api_key, options = {}) api_key ? @api_key = api_key : @api_key = MalauzaiPlaces.api_key @options = options end def places(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Place.list(lat, lng, @api_key, options), detail ) end private def collection_detail_level(places, detail = false) if detail places.map do |place| Place.find(place.place_id, @api_key, @options) end else places end end end end
class UserMailer < ApplicationMailer default from: 'notifications@example.com' def answer_email(user , question , answer) @user = user @question = question @answer = answer @url = "http://localhost:3000#{question_path(@question)}" mail(to: @user.email, subject: 'You have new answer to your question') end def accept_email(answer ,question) @answer = answer @question = question @user = answer.user url = "http://localhost:3000#{question_path(@question)}" mail(to: @user.email, subject: 'Your answer was accepted!') end end
module EasyExtensions class ExternalResources::ExternalResourceBase < ActiveResource::Base add_response_method :http_response def inspect "#<#{self.class.name} id=#{self.id}>" end end end
class GroupsController < ApplicationController before_action :replace_action, only: [:update,:edit] #renderメソッドは移動先のアクションの変数を持ってこなくてはならない。上記のreplace_actionはその変数をまとめたもの。 def index @groups = current_user.groups end def new @group = Group.new end def create @group = Group.new(post_params) if @group.save redirect_to :root, notice: "グループをさくせい" else @users = User.where.not(name: current_user.name) flash.now[:notice] = 'グループの作成にシッパイ' render :new end end def edit @users = User.where.not(name: current_user.name) # 補足ですが、コントローラーのインスタンス変数に@を付けるのは、単純に@が付いている変数がviewに渡されるというrailsの仕組みであるためです。 end def update group = Group.find(params[:id]) # / form_forタグに最初からupdateパスは埋め込まれている。すでにカラムが存在しているインスタンスならupdateアクションに自動的に振り分けられる。つまりパスを指定していたpictweetの<%= form_tag("/tweets/#{@tweet.id}", method: :patch ) do %>はform_forにおいてはいらないということになる if group.update(post_params) # flash.now[:notice]='グループを作成しました' redirect_to group_messages_path(group),notice: 'グループをさくせいしました' else flash.now[:notice]='グループの作成にシッパイ' render :edit # renderはbeforeアクションを呼ばない。だからbeforeアクションに記載していたコードを end end def search @users = User.search_like_name(params[:name]) # userモデルにscopeを使ってwhere文を渡している。順番としてはjs→コントローラー→model→コントローラー→js respond_to do|format| format.json end end private def post_params params.require(:group).permit(:name, user_ids:[]) # paramsの中身が"group"=>{"name"=>"ブルジョアソシエーション", "user_ids"=>["1", "2", "3", "4", "5", "2", "1"]}, "keyword"=>"", "commit"=>"Save"}なのでuser_idsは中身が配列になっているのでuser_ids[] end def replace_action @group = Group.find(params[:id]) end end
class TargetGroup < ActiveRecord::Base belongs_to :panel_provider belongs_to :parent, class_name: 'TargetGroup', dependent: :destroy has_many :children, class_name: 'TargetGroup', foreign_key: 'parent_id', dependent: :destroy has_and_belongs_to_many :countries scope :roots, -> { where(parent_id: nil) } def create_children(level = 2) return if level <= 0 0.upto(2) do TargetGroup.create(name: "TargetGroup", panel_provider: panel_provider, external_id: SecureRandom.hex, secret_code: SecureRandom.hex, parent: self) end children.sample.create_children(level-1) end end
require 'rails_helper' RSpec.feature "AddToCarts", type: :feature, js: true do before :each do @category = Category.create! name: 'Apparel' 10.times do |n| @category.products.create!( name: Faker::Hipster.sentence(3), description: Faker::Hipster.paragraph(4), image: open_asset('apparel1.jpg'), quantity: 10, price: 64.99 ) end User.create!( firstname: 'test', lastname: 'user', email: 'test_user@gmail.com', password: 'testuser', password_confirmation: 'testuser' ) end after(:each) do User.delete_all Product.delete_all Category.delete_all end scenario "The cart is updated" do # ACT visit root_path #Login to webpage click_on('Login') #Fill in form details fill_in 'email', :with => 'test_user@gmail.com' fill_in 'password', :with => 'testuser' #Submit form click_on('Submit') #click on product click_link('Add', match: :first) expect(page).to have_content 'My Cart (1)' save_screenshot end end
# http://www.mudynamics.com # http://labs.mudynamics.com # http://www.pcapr.net module Mu class Pcap class SCTP class Parameter < Packet attr_accessor :type, :size def initialize super @type = 0 @size = 0 end def self.from_bytes bytes # Basic validation Pcap.assert(bytes.length >= 4, "Truncated parameter header: 4 > #{bytes.length}") # Read chunk header type, size = bytes.unpack('nn') # Validate chunk size Pcap.assert(bytes.length >= size, "Truncated parameter: #{size} set, #{bytes.length} available") # Create chunk based on type case type when PARAM_IPV4 parameter = IpAddress.from_bytes(type, size, bytes[4..-1]) when PARAM_IPV6 parameter = IpAddress.from_bytes(type, size, bytes[4..-1]) when PARAM_STATE_COOKIE parameter = dummy_parameter(type, size, bytes) when PARAM_COOKIE_PRESERVATIVE parameter = dummy_parameter(type, size, bytes) when PARAM_HOST_NAME_ADDR parameter = dummy_parameter(type, size, bytes) when PARAM_SUPPORTED_ADDR_TYPES parameter = dummy_parameter(type, size, bytes) when PARAM_ECN parameter = dummy_parameter(type, size, bytes) when PARAM_RANDOM parameter = dummy_parameter(type, size, bytes) when PARAM_CHUNK_LIST parameter = dummy_parameter(type, size, bytes) when PARAM_HMAC_ALGORITHM parameter = dummy_parameter(type, size, bytes) when PARAM_PADDING parameter = dummy_parameter(type, size, bytes) when PARAM_SUPPORTED_EXTENSIONS parameter = dummy_parameter(type, size, bytes) when PARAM_FORWARD_TSN parameter = dummy_parameter(type, size, bytes) when PARAM_SET_PRIMARY_ADDR parameter = dummy_parameter(type, size, bytes) when PARAM_ADAPTATION_LAYER_INDICATION parameter = dummy_parameter(type, size, bytes) else parameter = dummy_parameter(type, size, bytes) end # Return the result return parameter end def write io, ip header = [@type, @size].pack('nn') # Write Parameter header followed by the payload io.write(header) io.write(@payload_raw) end def padded_size if 0 == @size % 4 return @size else return (@size + 4 - (@size % 4)) end end def to_s return "parameter(%d, %d)" % [@type, @size] end def self.dummy_parameter type, size, bytes # Create new dummy parameter parameter = Parameter.new parameter.type = type parameter.size = size # Save the payload parameter.payload = bytes[4..parameter.padded_size - 1] parameter.payload_raw = parameter.payload # Return the result return parameter end end # class Parameter end # class SCTP end # class Pcap end # module Mu require 'mu/pcap/sctp/parameter/ip_address'
class CommentsController < ApplicationController before_action :is_admin, only: [:create] def create @job_posting = JobPosting.find(params[:job_posting_id]) @comment = @job_posting.comments.create(comment_params) if @admin redirect_to admin_job_posting_path(@job_posting) else redirect_to user_job_posting_path(@job_posting) end end private def comment_params params.require(:comment).permit(:title, :body) end def is_admin port = request.fullpath.split("/")[1] @admin = (port == "admin") end end
module Qualifications include Reform::Form::Module property :skills_list property :certification_ids collection :educations, populate_if_empty: Education do # TODO: When Reform releases _destroy support implement that instead of this hack property :id, virtual: false property :_destroy, virtual: false property :degree_id property :field_of_study property :school validates :degree_id, presence: true validates :field_of_study, presence: true, length: { in: 2..256 } validates :school, presence: true, length: { in: 2..256 } end validate :education_length validate :skills_length validate :certifications_length # TODO: When Reform releases _destroy support implement that instead of this hack def save # you might want to wrap all this in a transaction super do |attrs| if model.persisted? to_be_removed = ->(i) { i[:_destroy] == '1' } ids_to_rm = attrs[:educations].select(&to_be_removed).map { |i| i[:id] } Education.destroy(ids_to_rm) educations.reject! { |i| ids_to_rm.include? i.id } end end # this time actually save super end private def education_length remaining_educations = educations.reject { |i| i._destroy == '1' } errors.add :base, 'At most 3 educations' if remaining_educations.size > 3 end def skills_length remaining_skills = skills_list.split(',') errors.add :base, 'At most 40 skills' if remaining_skills.size > 40 end def certifications_length errors.add :base, 'At most 10 certifications' if certification_ids.size > 10 end end
# Methods added to this helper will be available to all templates in the application. module ApplicationHelper def number_to_price(n) number_to_currency(n, :unit => 'zł') end def polish_paginate(collection) will_paginate collection, :prev_label => '&laquo; Poprzednie', :next_label => 'Następne &raquo;' end def ends_with_dot(text) text.gsub(/[^\!\.\?]$/, '\\0.') end def set_title(title) title = strip_tags(title) content_for :title, title end def show_title(title) set_title(title) content_tag :h1, title unless title.nil? end def polish_plural(value, t1, t2, t5) # 1 samochod value = value.to_i return t1 if value == 1 # 2, 3, 4, ..., 22, 23, ..., 104 samochody v = value > 20 ? value % 10 : value return t2 if [2,3,4].index v # 5, 6, ..., 10, 11, ..., 25 samochodow return t5 end # Awesome truncate # First regex truncates to the length, plus the rest of that word, if any. # Second regex removes any trailing whitespace or punctuation (except ;). # Unlike the regular truncate method, this avoids the problem with cutting # in the middle of an entity ex.: truncate("this &amp; that",9) => "this &am..." # though it will not be the exact length. def awesome_truncate(text, length = 30, truncate_string = "...") return if text.nil? l = length - truncate_string.chars.length text.chars.length > length ? text[/\A.{#{l}}\w*\;?/m][/.*[\w\;]/m] + truncate_string : text end def create_breadcrumb(name, options = nil) if options.is_a? String url = options elsif options.is_a? Hash url = url_for options elsif options.is_a? Array options.each do |name, url| add_breadcrumb name, url end url = nil else url = nil end return [name, url] end def before_breadcrumb(name, options = nil) @breadcrumbs ||= [] @breadcrumbs.insert 0, create_breadcrumb(name, options) end def add_breadcrumb(name, options = nil) @breadcrumbs ||= [] @breadcrumbs << create_breadcrumb(name, options) end def single_breadcrumb(txt, url, html_options = {}) unless url.nil? || url.empty? content_tag('li', link_to(strip_tags(txt), url), html_options) else content_tag('li', strip_tags(txt), html_options) end end def show_breadcrumbs(glue = '', html_options = {}) if @breadcrumbs s = [] s << single_breadcrumb('Jesteś tutaj:', nil, :class => 'first') @breadcrumbs[0..-2].each do |txt, url| s << single_breadcrumb(txt, url) end s << single_breadcrumb(@breadcrumbs.last[0], @breadcrumbs.last[1], :class => 'last') glue = content_tag('li', glue, :class => 'glue') unless glue.empty? content_tag 'ul', raw(s.join(glue)), html_options end end def layout_stylesheet stylesheet = controller.class.to_s.match('::') ? controller.class.to_s.gsub(/::.*/, '/').downcase : '' stylesheet + 'layout' end end
class ContentPage < ActiveRecord::Base extend FriendlyId friendly_id :url, use: :slugged validates :link_text, :url, :title, presence: true after_validation :move_friendly_id_error_to_url def to_s title end private def move_friendly_id_error_to_url errors.add :url, *errors.delete(:friendly_id) if errors[:friendly_id].present? end def should_generate_new_friendly_id? slug.blank? || url_changed? end end
class Admin::IdeaModeratorsController < Admin::IdeasBaseController cache_sweeper :idea_sweeper, :only => %w(destroy) before_filter :require_role_idea_instance_admin_of_instance helper_method :moderators, :instance_admins, :users, :user, :role def index respond_to do |format| format.html format.js do render :update do |page| page.replace_html "users", :partial => "user", :object => user, :locals => { :role_type => role } end end end end def create user.has_role role, instance user.has_role "idea_admin" user.has_role "admin" render_updated_roles end def destroy user.has_no_role role, instance unless user.has_role? opposite_role user.has_no_role "idea_admin" user.has_no_role "admin" end render_updated_roles end private def render_updated_roles render :update do |page| roled = role.sub(/^idea_/) {}.pluralize page.replace_html roled, :partial => "user", :collection => send(roled), :locals => { :role_type => role } end end # === Helper methods def moderators @moderators ||= User.permitted "idea_moderator", :authorizable => instance end def instance_admins @instance_admins ||= User.permitted "idea_instance_admin", :authorizable => instance end def user @user ||= if params[:screen_name] User.find_by_screen_name params[:screen_name] elsif params[:id] User.find params[:id].to_s[/\d+/] end end def role params[:role_type] end def opposite_role case role when "idea_moderator" then "idea_instance_admin" when "idea_instance_admin" then "idea_moderator" end end end
require 'azure_mgmt_compute' require 'azure_mgmt_resources' require 'azure_mgmt_storage' require 'azure_mgmt_network' # Include SDK modules to ease access to classes include Azure::ARM::Resources include Azure::ARM::Resources::Models include Azure::ARM::Compute include Azure::ARM::Compute::Models include Azure::ARM::Network include Azure::ARM::Network::Models include Azure::ARM::Storage include Azure::ARM::Storage::Models LOCATION = 'westeurope' TEST_NAME = 'ohmytest' tenant_id = ENV['ARM_TENANT_ID'] client_id = ENV['ARM_CLIENT_ID'] secret = ENV['ARM_SECRET'] subscription_id = ENV['ARM_SUBSCRIPTION_ID'] def authenticate(tenant_id, client_id, secret) token_provider = MsRestAzure::ApplicationTokenProvider.new(tenant_id, client_id, secret) credentials = MsRest::TokenCredentials.new(token_provider) end def create_storage_profile(storage_client, resource_group) storage_profile = StorageProfile.new storage_profile.image_reference = get_image_reference storage = create_storage_account(storage_client, resource_group) os_disk = OSDisk.new os_disk.caching = 'None' os_disk.create_option = 'fromImage' os_disk.name = 'Test' virtual_hard_disk = VirtualHardDisk.new virtual_hard_disk.uri = generate_os_vhd_uri storage.name os_disk.vhd = virtual_hard_disk storage_profile.os_disk = os_disk storage_profile end def generate_os_vhd_uri(storage_name) container_name = 'cont-' + TEST_NAME vhd_container = "https://#{storage_name}.blob.core.windows.net/#{container_name}" os_vhduri = "#{vhd_container}/#{TEST_NAME}.vhd" os_vhduri end def get_image_reference ref = ImageReference.new ref.publisher = 'Canonical' ref.offer = 'UbuntuServer' ref.sku = '14.04.3-LTS' ref.version = 'latest' ref end def create_storage_account(storage_client, resource_group) storage_name = 'storage' + TEST_NAME params = build_storage_account_create_parameters(storage_name, resource_group.location) result = storage_client.storage_accounts.create(resource_group.name, storage_name, params).value!.body result.name = storage_name #similar problem in dot net tests result end def build_storage_account_create_parameters(name, location) params = Azure::ARM::Storage::Models::StorageAccountCreateParameters.new params.location = location params.name = name props = Azure::ARM::Storage::Models::StorageAccountPropertiesCreateParameters.new params.properties = props props.account_type = 'Standard_GRS' params end def create_network_profile(network_client, resource_group) puts " + creating virtual network" vn = create_virtual_network(network_client, resource_group) puts " + creating subnet" subnet = create_subnet(vn, resource_group, network_client.subnets) puts " + creating network interface" network_interface = create_network_interface(network_client, resource_group, subnet) puts " + done" profile = NetworkProfile.new profile.network_interfaces = [network_interface] profile end def build_subnet_params params = Subnet.new prop = SubnetPropertiesFormat.new params.properties = prop prop.address_prefix = '10.0.1.0/24' params end def create_subnet(virtual_network, resource_group, subnet_client) subnet_name = 'subnet-' + TEST_NAME params = build_subnet_params subnet_client.create_or_update(resource_group.name, virtual_network.name, subnet_name, params).value!.body end def create_network_interface(network_client, resource_group, subnet) params = build_network_interface_param(network_client, resource_group, subnet) network_client.network_interfaces.create_or_update(resource_group.name, params.name, params).value!.body end def build_network_interface_param(network_client, resource_group, subnet) puts " - building params" network_interface_name = 'nic-' + TEST_NAME ip_configuration = create_ip_configuration(network_client, resource_group, subnet) nsg = create_network_security_group(network_client, resource_group) props = NetworkInterfacePropertiesFormat.new props.ip_configurations = [ip_configuration] props.network_security_group = nsg params = NetworkInterface.new params.location = resource_group.location params.name = network_interface_name params.properties = props params end def create_network_security_group(network_client, resource_group) sr_props = SecurityRulePropertiesFormat.new sr_props.priority = 100 sr_props.source_port_range = '1-65000' sr_props.destination_port_range = '1-65000' sr_props.source_address_prefix = '*' sr_props.destination_address_prefix = '*' sr_props.protocol = 'Tcp' # 'Udp' or '*' sr_props.access = 'Deny' sr_props.direction = 'Inbound' # 'Outbound' sr = SecurityRule.new sr.properties = sr_props sr.name = "sr-#{TEST_NAME}" props = NetworkSecurityGroupPropertiesFormat.new props.security_rules = [sr] nsg = NetworkSecurityGroup.new nsg.properties = props nsg.location = resource_group.location nsg = network_client.network_security_groups.create_or_update(resource_group.name, resource_group.name, nsg).value!.body # create_security_rules(network_client, nsg, resource_group) nsg end def update_security_group(network_client, nsg) sr_props = SecurityRulePropertiesFormat.new sr_props.priority = 100 sr_props.source_port_range = '1-65000' sr_props.destination_port_range = '1-65000' sr_props.source_address_prefix = '*' sr_props.destination_address_prefix = '*' sr_props.protocol = 'Tcp' # 'Udp' or '*' sr_props.access = 'Allow' sr_props.direction = 'Inbound' # 'Outbound' sr = SecurityRule.new sr.properties = sr_props sr.name = "sr-#{TEST_NAME}" nsg.properties.security_rules = [sr] name = TEST_NAME network_client.network_security_groups.create_or_update(name, name, nsg).value!.body end def create_security_rules(network_client, security_group, resource_group) props = SecurityRulePropertiesFormat.new props.priority = 100 props.source_port_range = '1-65000' props.destination_port_range = '1-65000' props.source_address_prefix = '*' props.destination_address_prefix = '*' props.protocol = 'Tcp' # 'Udp' or '*' props.access = 'Deny' props.direction = 'Inbound' # 'Outbound' sr = SecurityRule.new sr.properties = props sr.name = "sr-#{TEST_NAME}" network_client.security_rules.create_or_update(resource_group.name, security_group.name, sr.name, sr).value!.body end def create_ip_configuration(network_client, resource_group, subnet) puts " - creating ip" ip_configuration = NetworkInterfaceIpConfiguration.new ip_configuration_properties = NetworkInterfaceIpConfigurationPropertiesFormat.new ip_configuration.properties = ip_configuration_properties ip_configuration.name = 'ip_name-' + TEST_NAME ip_configuration_properties.private_ipallocation_method = 'Dynamic' ip_configuration_properties.public_ipaddress = create_public_ip_address(network_client, resource_group) ip_configuration_properties.subnet = subnet ip_configuration end def build_public_ip_params(location) public_ip = PublicIpAddress.new public_ip.location = location props = PublicIpAddressPropertiesFormat.new props.public_ipallocation_method = 'Dynamic' domain_name = 'domain-' + TEST_NAME # dns_settings = PublicIpAddressDnsSettings.new # dns_settings.domain_name_label = domain_name # props.dns_settings = dns_settings public_ip.properties = props public_ip end def create_public_ip_address(network_client, resource_group) public_ip_address_name = 'ip_name' + TEST_NAME params = build_public_ip_params(resource_group.location) network_client.public_ip_addresses.create_or_update(resource_group.name, public_ip_address_name, params).value!.body end def build_virtual_network_params(location) params = VirtualNetwork.new props = VirtualNetworkPropertiesFormat.new params.location = location address_space = AddressSpace.new address_space.address_prefixes = ['10.0.0.0/16'] props.address_space = address_space # dhcp_options = DhcpOptions.new # dhcp_options.dns_servers = %w(10.1.1.1 10.1.2.4) # props.dhcp_options = dhcp_options # sub2 = Subnet.new # sub2_prop = SubnetPropertiesFormat.new # sub2.name = "subnet-#{TEST_NAME}" # sub2_prop.address_prefix = '10.0.2.0/24' # sub2.properties = sub2_prop # props.subnets = [sub2] params.properties = props params end def create_virtual_network(network_client, resource_group) virtualNetworkName = "vnet-#{TEST_NAME}" params = build_virtual_network_params(resource_group.location) network_client.virtual_networks.create_or_update(resource_group.name, virtualNetworkName, params).value!.body end def get_virtual_machine(compute_client, resource_group_name, vm_name) compute_client.virtual_machines.get(resource_group_name, vm_name, 'instanceView').value!.body end def create_virtual_machine(compute_client, network_client, storage_client, resource_group) puts " * building OS profile" os_profile = OSProfile.new os_profile.computer_name = TEST_NAME os_profile.admin_username = TEST_NAME os_profile.admin_password = 'P@ssword1' puts " * building hardware profile" hardware_profile = HardwareProfile.new hardware_profile.vm_size = 'Standard_A0' props = VirtualMachineProperties.new props.os_profile = os_profile props.hardware_profile = hardware_profile puts " * building network profile" props.network_profile = create_network_profile(network_client, resource_group) puts " * building storage profile" props.storage_profile = create_storage_profile(storage_client, resource_group) params = VirtualMachine.new params.type = 'Microsoft.Compute/virtualMachines' params.properties = props params.location = resource_group.location puts " * deploying VM" promise = compute_client.virtual_machines.create_or_update(TEST_NAME, TEST_NAME, params) result = promise.value! result.body end def resource_group_exists?(resources_client, rg_name) promise = resources_client.resource_groups.check_existence(rg_name) result = promise.value! resource_group = result.body end def resource_group_delete(resources_client, rg_name) promise = resources_client.resource_groups.delete(rg_name) result = promise.value! result.body end def get_ip_address(network_client, name) network_client.public_ip_addresses.get(name, 'ip-' + name) end def get_security_rules(network_client, name) network_client.security_rules.list(name, name).value!.body end def get_security_group(network_client, name) network_client.network_security_groups.get(name, name).value!.body end def get_inex_security_group(network_client, name) network_client.network_security_groups.get(name, name+'-nonexisting').value!.body end begin puts "Azure ARM. Authenticating with params: tenant_id: #{tenant_id} , client_id: #{client_id} , secret: #{secret}" credentials = authenticate(tenant_id, client_id, secret) puts "Got credentials: #{credentials.to_s}" # Create a compute client compute_client = ComputeManagementClient.new(credentials) compute_client.subscription_id = subscription_id # Create a resources client resources_client = ResourceManagementClient.new(credentials) resources_client.subscription_id = subscription_id # Create a storage client storage_client = StorageManagementClient.new(credentials) storage_client.subscription_id = subscription_id # Create a network client network_client = NetworkResourceProviderClient.new(credentials) network_client.subscription_id = subscription_id puts "List all vms in the subscription..." promise = compute_client.virtual_machines.list_all result = promise.value! list = result.body.value puts " * Response (#{list.count} vms) : #{list}" # puts "Deleting all (#{list.count}) vms in the subscription..." unless list.empty? # # Delete the resource group, and all other resources will be deleted on cascade # list.each do |vm| # promise = resources_client.resource_groups.delete(vm.name) # result = promise.value! # puts " * Deleted #{vm.name} : #{result.body}" # end puts "Checking existence of resource group named '#{TEST_NAME}' ..." rgpresent = resource_group_exists?(resources_client, TEST_NAME) puts " * Resource group '#{TEST_NAME}'#{rgpresent ? '' : ' not'} present" if rgpresent puts "Deleting resource group named '#{TEST_NAME}' ..." resource_group_delete(resources_client, TEST_NAME) puts " * Resource group #{TEST_NAME} deleted" end puts "Creating a resource group named '#{TEST_NAME}' ..." resource_group = Azure::ARM::Resources::Models::ResourceGroup.new() resource_group.location = LOCATION promise = resources_client.resource_groups.create_or_update(TEST_NAME, resource_group) result = promise.value! resource_group = result.body puts " * Created #{resource_group.name} with id '#{resource_group.id}' (#{resource_group.location})" puts "Creating a virtual machine named '#{TEST_NAME}' ..." vm = create_virtual_machine(compute_client, network_client, storage_client, resource_group) puts " * Created #{vm.name} with id : '#{vm.id}'" puts "Getting a virtual machine named '#{TEST_NAME}' ..." vm = get_virtual_machine(compute_client, TEST_NAME, TEST_NAME) puts " * Got #{vm} with id : '#{vm.id}'" puts "Getting assigned public ip address for virtual machine named '#{TEST_NAME}' ..." ip = get_ip_address(network_client, TEST_NAME) puts " * Got #{ip}" puts "Getting security rules for virtual machine named '#{TEST_NAME}' ..." srs = get_security_rules(network_client, TEST_NAME) puts " * Got #{srs}" puts "Getting security group for virtual machine named '#{TEST_NAME}' ..." nsg = get_security_group(network_client, TEST_NAME) puts " * Got #{nsg}" puts "Updating security group for virtual machine named '#{TEST_NAME}' ..." unsg = update_security_group(network_client, nsg) puts " * Got #{unsg}" # puts "Getting inexistent security group for virtual machine named '#{TEST_NAME}' ..." # nensg = get_inex_security_group(network_client, TEST_NAME) # puts " * Got #{nensg}" rescue MsRestAzure::AzureOperationError => ex puts "MsRestAzure::AzureOperationError : " puts " * request: #{ex.request}" puts " * response: #{ex.response}" puts " * body: #{ex.body}" puts ex end
class OneTimeEmail < ActiveRecord::Base belongs_to :user validates_uniqueness_of :key, :scope => :user_id after_create :deliver_mail protected def deliver_mail ETTriggeredSendAdd.send_badge_level_up_notification(self.user) if App.sywr_enabled? 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 protect_from_forgery except: :gallery_web_address def gallery_web_address @customers = Customer.all .where(web_page_viewable: true) .map { |c| { name: c.note, gallery_web_address: c.gallery_web_address } } respond_to do |format| format.js { render json: @customers, callback: params['callback'] } format.json { render json: @customers } end end end
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) TeaItem.create([ { "image": "https://media.steepster.com/api/file/WRjUCwsPRaizfhwgIdML/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/whispering-pines-tea-company/43095-golden-orchid", "description": "Dark Bittersweet, Dark Chocolate, Dates, Fruity, Nutty, Cocoa, Malt, Smoke, Vanilla, Bergamot, Floral, Honeysuckle, Orchid, Olive Oil, Pine, White Chocolate, Honey, Baked Bread, Drying, White Grapes, Bitter, Caramel, Plums, Sweet, Smooth, Dark Wood, Chocolate, Earth, Brown Toast, Creamy, Cream, Graham, Stonefruits, Toasted Rice, Peat, Cherry, Pepper, Apricot, Graham Cracker", "price": 179, "type": "Black", "name": "Golden Orchid Whispering Pines Tea Company" }, { "image": "https://media.steepster.com/api/file/ip0MWYJRpapza3tw8yOZ/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/california-tea-house/3166-golden-monkey-paw", "price": 32, "type": "Black", "name": "Golden Monkey Paw California Tea House" }, { "image": "https://media.steepster.com/api/file/nszoX2ewRlyJx71ntgRa/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/fong-mong-tea-shop/27249-hand-plucked-top-grade-oriental-beauty-oolong-tea", "price": 13, "type": "Yerba Maté", "description": "Oolong, Oolong Tea, Oolong Tea Leaves", "name": "Hand-plucked TOP GRADE Oriental Beauty Oolong Tea FONG MONG TEA SHOP" }, { "image": "https://media.steepster.com/api/file/SfGZsG4SQgyOqlmiSQnp/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/butiki-teas/34422-taiwanese-wild-mountain-black", "price": 212, "type": "White", "description": "Honey, Sweet Potatoes, Tea, Apple Candy, Caramel, Apricot, Brown Sugar, Burnt Sugar, Butter, Cinnamon, Dried Fruit, Grain, Pastries, Raisins, Fruity, Sweet, Baked Bread, Yams, Chocolate, Stonefruits, Cocoa, Malt, Vanilla, Cream, Smooth", "name": "Taiwanese Wild Mountain Black Butiki Teas" }, { "image": "https://media.steepster.com/api/file/sKj8iB9TVCsBBkeehxqp/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/mandala-tea/29244-wild-monk-sheng-puer-2012", "price": 65, "type": "Rooibos", "description": "Tobacco, Fruity, Smoke, Sweet, Wood, Apricot, Bamboo, Wet Moss, Butter, Flowers, Molasses, Sage, Straw, Cinnamon, Earth, Licorice, Nuts, Sweet Potatoes, Yams, Creamy, Hay, Musty, Toasted, Wet Earth, Wet wood", "name": "Wild Monk Sheng Pu'er (2012) Mandala Tea" }, { "image": "https://media.steepster.com/api/file/iegc8CQcRay5JeHT0eEM/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/whispering-pines-tea-company/48325-the-jabberwocky", "price": 68, "type": "Rooibos", "description": " Apricot, Baked Bread, Dried Fruit, Malt, Wood, Brown Toast, Camphor, Caramel, Chocolate, Cream, Eucalyptus, Fruity, Honey, Orange, Peach, Raisins, Sweet Potatoes, Burnt Sugar, Cocoa, Smooth, Stonefruits, Sweet, Dark Chocolate, Mineral, Musty, Tannin, Tea, Brown Sugar, Citrus, Molasses, Corn Husk, Salt, Cinnamon, Creamy, Broth, Cherry, Dates, Muscatel, Red Fruits, Wet Wood, Plums, Berry, Grain, Cherry Wood, Oak wood, Floral, Yams, Mint, Toast, Custard, Earth, Thick", "name": "The Jabberwocky Whispering Pines Tea Company" }, { "image": "https://media.steepster.com/api/file/84cnuVtQM2H3tOExihbL/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/verdant-tea/20060-hand-picked-tieguanyin-spring-oolong-2011", "price": 60, "type": "Oolong", "description": "Flowers, Berries, Berry, White Chocolate, Floral", "name": "Hand Picked Tieguanyin Spring Oolong (2011) Verdant Tea" }, { "image": "https://media.steepster.com/api/file/b4ZgPkFhRLGDMcFmgu9h/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/butiki-teas/41171-hello-sweetie", "price": 140, "type": "Matcha", "description": "Coconut, Cream, Creamy, Fruity, Malt, Milk, Smooth, Tannin, Tropical, Vanilla, Pastries, banana, Sweet, Butter, Caramel, Nutty, Tea, Toasted, Apple Candy, Banana, Candy, Cookie, Toffee, Almond, Honey, Nuts, Sugar", "name": "Hello Sweetie Butiki Teas" }, { "image": "https://media.steepster.com/api/file/kL8dCqJrTAW8ifk9QnNc/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/white-2-tea/65303-2015-last-thoughts", "price": 10, "type": "Matcha", "description": "Floral, Rainforest, Honeysuckle, Orchids, Pepper, Sweet, Winter Honey, Zucchini, Apple Skins, Grapes, Lemon, Peppercorn, Vegetal, Vinegar", "name": "2015 Last Thoughts White 2 Tea" }, { "image": "https://media.steepster.com/api/file/0vAf5X4Si6wSXhc4xOms/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/whispering-pines-tea-company/48058-cocoa-amore", "price": 65, "type": "Matcha", "description": "Apple, Autumn Leaf Pile, Dark Bittersweet, Green Wood, Cherry, Chocolate, Cocoa, Dark Chocolate, Earth, Flowers, Forest Floor, Grass, Vanilla, Almond, Blackberry, Baked Bread, Dill, Grain, Raisins, Creamy, Malt, Smooth, Sweet", "name": "Cocoa Amore Whispering Pines Tea Company" }, { "image": "https://media.steepster.com/api/file/Xt8U6g8YRRuJNYqEIkp4/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/white-2-tea/65305-2015-bosch", "price": 8, "type": "Honeybush", "description": " Almond, Butter, Plums, Kettle Corn, Pepper, Red Wine, Smooth, Spices, Sweet, Bitter Melon, Green, Honey, Nutmeg, Vanilla, Bitter, Eucalyptus, Floral, Herbs", "name": "2015 Bosch White 2 Tea" }, { "image": "https://media.steepster.com/api/file/Hat4DLjkTl6tyb3Hn53H/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/mandala-tea/22442-milk-oolong", "price": 112, "type": "Honeybush", "description": "Butter, Green, Popcorn, Sugar, Coconut, Smooth, Vegetal, Milk, Butterscotch, Roasted, Toasted Rice, Bergamot, Candy, Creamy, Dry Grass, Mango, Pineapple, Strawberry, Sweet, Tropical, Vanilla, Asparagus, Cream, Caramel, Orchid, Floral, Grass, Toffee, Burnt Sugar, Gardenias, Peas, Brown Sugar, Cotton Candy, Flowers, Berries, Fruity, Dried Fruit, Green Apple, Mineral, Sugarcane, Sweet, warm grass, Tart, Heavy, Peach, Honey, Stewed Fruits, Fruit Tree Flowers, Yams", "name": "Milk Oolong Mandala Tea" }, { "image": "https://media.steepster.com/api/file/EMbK7q8WTtjtWGTBNd7n/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/zhi-tea/15759-gong-fu-black", "price": 60, "type": "Herbal", "description": "Caramel, Cocoa, Smooth, Malt, Fruity, Astringent, Muscatel, Baked Bread, Chocolate, Tea, Walnut", "name": "Gong Fu Black Zhi Tea" }, { "image": "https://media.steepster.com/api/file/eXa2B8fyRnOCpxls5Qhb/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/butiki-teas/28779-premium-taiwanese-assam", "price": 285, "type": "Herbal", "description": "Tea, Chocolate, Cream, Cocoa, Fruity, Malt, Brown Sugar, Burnt Sugar, Caramel, Dried Fruit, Molasses, Raisins, Baked Bread, Vanilla, Cinnamon, Honey, Cherry, Pastries, Sweet, Sweet Potatoes, Fig, Grain, Plums, Yams, Strawberry", "name": "Premium Taiwanese Assam Butiki Teas" }, { "image": "https://media.steepster.com/api/file/56YhlwW6S8SWCNihRaHg/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/naivetea/4478-passionfruit-oolong", "price": 27, "type": "Guayusa", "description": "Natural Passionfruit Extract, Oolong, Passionfruit", "name": "Passionfruit Oolong Naivetea" }, { "image": "https://media.steepster.com/api/file/mMoahDdUS7y5Vw1s7LSO/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/kroger-private-selection/15893-passion-fruit-and-papaya-black-tea", "price": 11, "type": "Guayusa", "description": "Fruity", "name": "Passion Fruit & Papaya black tea Kroger Private Selection" }, { "image": "https://media.steepster.com/api/file/fMD1aoEFRESwtu0aMbLp/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/zen-tea/30489-earl-grey-cream", "price": 115, "type": "Guayusa", "description": "", "name": "Earl Grey Cream Zen Tea" }, { "image": "https://media.steepster.com/api/file/VYXn4y9MSIeUuiJzpoQt/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/whispering-pines-tea-company/57738-ambrosia", "price": 13, "type": "Green", "description": "Blackberry, Creamy, Earl Grey, Bergamot, Vanilla, Cream, Pepper", "name": "Ambrosia Whispering Pines Tea Company" }, { "image": "https://media.steepster.com/api/file/p17qzXLQ6adt8gtugXw7/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/the-phoenix-collection/28976-silver-bud-white-pu-erh-big-snow-mountain-da-xue-shan-2003", "price": 6, "type": "Green", "description": "", "name": "Silver Bud White Pu-erh - Big Snow Mountain (Da Xue Shan) 2003 The Phoenix Collection" }, { "image": "https://media.steepster.com/api/file/TOwBmaJHThSZ5OzXP01g/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/butiki-teas/28778-mi-xian-black", "price": 134, "type": "Black", "description": "", "name": "Mi Xian Black Butiki Teas" }, { "image": "https://media.steepster.com/api/file/Q2StB6vfSFerohZnCoew/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/white-2-tea/65307-2015-colbert-holland-1945", "price": 5, "type": "Fruit", "description": "Butter, Creamy, Fruity, Spices, Straw, Thick, Vegetal, Earth, Forest Floor, Green, Sugarcane, Sweet, warm grass, Wet Moss, Asparagus, Tobacco", "name": "2015 Colbert Holland 1945 White 2 Tea" }, { "image": "https://media.steepster.com/api/file/t0spKxCTTGz98Iehhr8Q/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/verdant-tea/27623-zhu-rong-yunnan-black", "price": 271, "type": "Fruit", "description": "Burnt, Cinnamon, Roasted, Brown Sugar, Cedar, Chocolate, Cream, Honey, Lemon Zest, Malt, Marzipan, Mineral, Nutmeg, Orange, Pine, Roasted nuts, Toast, Vanilla, Wheat, Cacao, Creamy, Dark Bittersweet, Campfire, Caramel, Fruity, Milk, Plums, Sweet, Umami, Wet Earth, Whiskey, Wood, Cocoa, Grain, Nuts, Sweet Potatoes, Raisins, Tobacco, Marshmallow, Spicy, Smoke, Baked Bread, Dark Chocolate, Yeast, Citrus, Berries, Coffee, Molasses, Graham Cracker, Muscatel, Peppercorn, Earth", "name": "Zhu Rong Yunnan Black Verdant Tea" }, { "image": "https://media.steepster.com/api/file/Lc2XLbx4SWGPngCF4Vf5/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/california-tea-house/3164-white-monkey-paw", "price": 5, "type": "Fruit", "description": "Butter, Grass", "name": "White Monkey Paw California Tea House" }, { "image": "https://media.steepster.com/api/file/7yz7myJrQuCPyPZ6tqZg/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/lupicia/8743-gyokuro-pine-breeze", "price": 7, "type": "Food", "description": "Creamy, Honey, Nectar, Smooth, Sweet, Sweet, warm grass, Umami, Vegetal", "name": "Gyokuro Pine Breeze Lupicia" }, { "image": "https://media.steepster.com/api/file/0gf9HVS3Q2GZn3caPZUb/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/rosali-tea/69575-milk-oolong", "price": 4, "type": "Flowering", "description": "Butter, Green, Cream, Milk, Smooth, Creamy", "name": "Milk Oolong Rosali Tea" }, { "image": "https://media.steepster.com/api/file/T1rdJhT9T8WnhsrdcgvO/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/fong-mong-tea-shop/27245-alishan-high-mt-oolong-tea", "price": 8, "type": "Flowering", "description": "Cream, Fruit Tree Flowers, Honey, Peach, Anise, Cinnamon, Floral, Sweet, Flowers", "name": "Alishan High Mt. Oolong Tea FONG MONG TEA SHOP" }, { "image": "https://media.steepster.com/api/file/NaeUPhhwQxmO0mx4gTim/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/white-2-tea/35985-2012-giant-steps-old-arbor-puer-blend", "price": 6, "type": "Chai", "description": "", "name": "2012 Giant Steps Old Arbor Puer Blend White 2 Tea" }, { "image": "https://media.steepster.com/api/file/uUo2krH6TKaPqCs9BoqN/convert?fit=crop&h=200&w=350", "link": "http://steepster.com/teas/afri-tea-and-coffee-blenders-1963-ltd/2031-african-pride-tea", "price": 12, "type": "Chai", "description": "", "name": "African Pride Tea Afri Tea and Coffee Blenders (1963) Ltd" } ])
class GoogledriveController < ApplicationController protect_from_forgery except: :get_docs # get_docsアクションを除外 def index @files = GoogleDriveDatum.order('fullpath') end def docs @files = GoogleDriveDatum.where("content <> ''").order('fullpath') end def get_docs ajax_action unless params[:ajax_handler].blank? # Ajaxリクエストではない時の処理 end def ajax_action if params[:ajax_handler] == 'handle_name1' # Ajaxの処理 id = params[:id] @data = GoogleDriveDatum.find(id) @output_html = "表示不可" if @data.content != "" File.open(@data.content, "r") do |f| @output_html = f.read end end render end end end