text stringlengths 10 2.61M |
|---|
class Micropost < ActiveRecord::Base
attr_accessible :content
belongs_to :user
validates :content, :presence => true, :length => { :maximum => 140 }
validates :user_id, :presence => true
default_scope :order => 'microposts.created_at DESC'
scope :from_users_followed_by, lambda { |user| followed_by(user) }
private
def self.followed_by(user)
following_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN (#{following_ids}) OR user_id = :user_id",
{ :user_id => user })
end
end
|
module DelegateCached
class TargetInstaller < Installer
def install_instance_methods
install_update_method
install_callback unless options[:no_callback] || options[:polymorphic]
end
def install_update_method
@target.model.class_eval %(
def #{update_method_name}
#{update_method_body}
end
)
end
def install_callback
@target.model.class_eval %(
after_save :#{update_method_name}, if: :#{@target.column}_changed?
)
end
def update_method_name
'update_delegate_cached_value_for_' \
"#{@source.plural_underscored_model_name}_#{@source.column}"
end
def update_method_body
case @source.reflection.macro
when :belongs_to
update_method_body_for_has_one_or_has_many
when :has_one
update_method_body_for_belongs_to
end
end
def update_all_line
".update_all(#{@source.column}: #{@target.column})"
end
def update_method_body_for_has_one_or_has_many
%(
#{@source.model}.where(#{@source.association}_id: id)
#{update_all_line}
)
end
def update_method_body_for_belongs_to
%(
#{@source.model}.where(id: #{@target.association}_id)
#{update_all_line}
)
end
end
end
|
class ApplicationController < ActionController::Base
before_action :current_cart, :current_checkout, :current_customer, :current_seller
def current_cart
@current_cart ||= Cart.new()
end
helper_method :current_cart
def current_checkout
@current_checkout ||= Checkout.new()
end
helper_method :current_checkout
def current_customer
@current_customer ||= Customer.new()
end
helper_method :current_customer
def current_seller
@current_seller ||= Seller.new()
end
helper_method :current_seller
end
|
module Github
class LanguagesRepository
include FaradayClient
def all(username)
repos = get_user_repos(username)
return nil, 'languages cannot be fetched' if repos.nil?
languages = repos.map { |r| get_languages(username, r['name']) }
return nil, 'languages cannot be fetched' unless languages.all?
initial_hash = Hash.new {|h,k| h[k] = 0}
languages.reduce(initial_hash) do |aggregated_hash, languages_list|
languages_list.each do |language, count|
aggregated_hash[language] += count
end
aggregated_hash
end
end
private
def get_languages(username, repo)
response = client.get("/repos/#{username}/#{repo}/languages")
return unless response.success?
JSON.parse(response.body)
rescue JSON::ParserError => e
Rails.logger.info "Error while parsing response from GitHub: #{e.message}"
nil
end
def get_user_repos(username)
response = client.get("/users/#{username}/repos")
return unless response.success?
JSON.parse(response.body)
rescue JSON::ParserError => e
Rails.logger.info "Error while parsing response from GitHub: #{e.message}"
nil
end
end
end
|
class Genre < ApplicationRecord
has_many :hobbies
end
|
class ChangeIntouchTelegramChatSubscriptionsChatIdType < Rails.version < '5.0' ? ActiveRecord::Migration : ActiveRecord::Migration[[Rails::VERSION::MAJOR, Rails::VERSION::MINOR].join('.')]
def change
change_column :intouch_telegram_chat_subscriptions, :chat_id, :bigint
end
end
|
module Forums
class ThreadPresenter < BasePresenter
presents :thread
def created_by
@created_by ||= present(thread.created_by)
end
def link(options = {})
link_to(thread.title, forums_thread_path(thread), options)
end
def breadcrumbs
crumbs = path_objects.map { |path| content_tag(:li, path, class: 'breadcrumb-item') }
safe_join(crumbs, '')
end
def created_at
thread.created_at.strftime('%c')
end
def created_at_in_words
time_ago_in_words thread.created_at
end
def status_classes
cls = []
cls << 'locked-thread' if thread.locked
cls << 'hidden-thread' if thread.hidden
cls << 'pinned-thread' if thread.pinned
safe_join(cls, ' ')
end
def status_icons
icons = []
icons << locked_icon if thread.locked
icons << hidden_icon if thread.hidden
icons << pinned_icon if thread.pinned
safe_join(icons, '')
end
def to_s
thread.title
end
private
def path_objects
present_collection(thread.path).map(&:link)
end
def locked_icon
inline_svg_tag('open_iconic/lock-locked.svg', title: 'Locked', class: 'icon fill-secondary mr-1')
end
def hidden_icon
inline_svg_tag('eye-hide.svg', title: 'Hidden', class: 'icon fill-secondary mr-1')
end
def pinned_icon
inline_svg_tag('open_iconic/pin.svg', title: 'Pinned', class: 'icon fill-success mr-1')
end
end
end
|
require File.dirname(__FILE__) + '/../../test_helper'
class Qa::QuestionPhotoControllerTest < ActionController::TestCase
def setup
App.stub!(:qa_moderation_enabled, :return => false)
@logged_in_user = users(:matt)
@uploaded_question_photo = {:uploaded_question_photos => "a,b,c,d"}
@session_hash = generate_test_session_hash(@logged_in_user)
end
test "should create a new Photo and assign current photo upload size from session hash" do
get :new,{}, @session_hash.merge(@uploaded_question_photo)
assigns(:photo).should_not == nil
assigns(:current_photo_upload_size).should == @uploaded_question_photo[:uploaded_question_photos].split(',').size
end
test "should create a new photo with session params" do
LocalPhoto.class_eval do def convert_all; true; end; end
image = Tempfile.new("some.jpg")
def image.content_type
'image/jpg'
end
post :create, {"photo"=>{"file_object"=> image, "caption"=>"this is the caption"}}, @session_hash
assert LocalPhoto.find_by_caption('this is the caption')
end
end
|
class Health < ApplicationRecord
DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
belongs_to :baby, inverse_of: :healths
validates :weight, presence: true
validates :height, presence: true
before_save :calculate_age
def calculate_age
return if baby.blank?
borrowed_month = false
current_date = Time.new
birth_date = Time.parse(baby.date_of_birth)
# Get days for this year
if current_date.to_date.leap?
DAYS_IN_MONTH[2] = 29
end
day = current_date.day - birth_date.day
month = current_date.month - birth_date.month
year = current_date.year - birth_date.year
if day < 0
# subtract month, get positive # for day
day = DAYS_IN_MONTH[birth_date.month] - birth_date.day + current_date.day
month -= 1
borrowed_month = true
end
if month < 0
# subtract year, get positive # for month
month = 12 - birth_date.month + current_date.month
if borrowed_month == true
month -= 1
end
year -= 1
end
if year < 0
year, month, day = 0, 0, 0
end
self.age = (year*12)+ month + (day>20 ? 1 : 0)
self.baby.update(age: self.age)
end
end
|
class Shop < ApplicationRecord
validates :shop_name, presence: true
has_many :points,
foreign_key: :payer_id
end
|
class Target
attr_reader :url, :method
attr_accessor :resp, :body
# resp.body strore the original body, @body store the parsed body
def initialize(url_str, query_str, method)
@url = url_parse(append_query(url_str, query_str))
@method = method
@body = nil
end
def parse_body(local,localport)
# add a basetag
basetag = '<base href="http://' + local + ':' + localport.to_s + '/http://' + @url.host + '/"/></head>'
@body.gsub!(/<\/head>/i, basetag)
# change all links in the page
@body.gsub!(/(src=|href=)["'](.*?)["']/) { |x|
# try to parse as URL
# FIXME here I rescue an error but nothing more
begin
oldurl = URI.parse($2)
rescue URI::InvalidURIError
oldurl = $2
end
case oldurl
when URI then
if oldurl.absolute? then
newurl = $1 + "\"" + "http://" + local + ':' + localport.to_s + "/" + $2 + "\""
else
newurl = $1 + "\"" + "http://" + local + ':' + localport.to_s + "/http://" + @url.host + "/" + $2 + "\""
end
end
}
end
private
def url_parse(uri_str)
url = URI.parse(uri_str)
if url.path == "" then
url.path= '/index.html'
end
return url
end
def append_query(url_str, query_str)
case query_str
when "", nil then return url_str
else
return url_str + '?' + query_str
end
end
end
|
require './src/tokenizer/lexer'
require './src/tokenizer/errors'
require './spec/contexts/lexer'
RSpec.describe Tokenizer::Lexer, 'error handling' do
include_context 'lexer'
describe '#next_token' do
it 'raises an error when too much indent' do
mock_reader(
"インデントしすぎるとは\n" \
" 行頭の空白は 「多い」\n"
)
expect_error Tokenizer::Errors::UnexpectedIndent
end
it 'raises an error when the BOF is indented' do
mock_reader(
" ホゲは 1\n"
)
expect_error Tokenizer::Errors::UnexpectedIndent
end
end
end
|
class User < ApplicationRecord
# encrypt password
has_secure_password
validates_presence_of :email, :password_digest
validates_email_format_of :email, :message => 'invalid email address'
def generate_password_token!
self.reset_password_token = generate_token
self.reset_password_sent_at = Time.now.utc
save!
end
def password_token_valid?
(self.reset_password_sent_at + 4.hours) > Time.now.utc
end
def reset_password!(password)
self.reset_password_token = nil
self.reset_password_sent_at = nil
self.password = password
save!
end
private
def generate_token
SecureRandom.hex(10)
end
end
|
require "digest"
class Client < ActiveRecord::Base
validates_length_of :username, :within => 3..40
validates_length_of :name, :maximum => 50
validates_length_of :email, :maximum => 50
validates_uniqueness_of :username
validates_presence_of :name, :username, :email, :salt, :time_zone
validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "Invalid email."
# different validations for password, password_confirmation based on type of action
validates_length_of :password, :within => 4..40, :on => :create
validates_confirmation_of :password, :on => :create
validates_length_of :password, :within => 4..40, :on => :update, :if => :password_required?
validates_confirmation_of :password, :on => :update, :if => :password_required?
validates_presence_of :password, :password_confirmation, :on => :update, :if => :password_required?
attr_protected :id, :salt
attr_accessor :password, :password_confirmation
has_many :badges
has_many :badge_images
has_many :feats
has_many :user_badges
has_many :user_feats
has_many :client_stats
def active_badges(options={})
return Badge.find(:all, :conditions => {:client_id => self.id, :active => true }, :include => :badges_feats)
end
def active_feats(options={})
return Feat.find(:all, :conditions => {:client_id => self.id, :active => true })
end
def self.active_clients(options={})
return Client.find(:all, :conditions => {:active => true })
end
# Summarization
def self.summarize_active_clients
clients = Client.active_clients
for client in clients
Time.zone = client.time_zone
client.summarize(1.days.ago.beginning_of_day, 1.days.ago.end_of_day)
# extra day to handle some time zones (for now)
client.summarize(2.days.ago.beginning_of_day, 2.days.ago.end_of_day)
end
end
# only summarizes one day at a time (for now)
def summarize(start_time, end_time)
logger.info("Summarizing #{self.name} (#{self.id}): #{start_time} to #{end_time}")
badges = UserBadge.count(
:conditions => ["client_id = ? AND created_at BETWEEN ? AND ?", self.id, start_time, end_time])
feats = UserFeat.count(
:conditions => ["client_id = ? AND created_at BETWEEN ? AND ?", self.id, start_time, end_time])
# odd behavior of ActiveRecord count - need to do this ...
users = UserFeat.count(
:group => :user_id,
:conditions => ["client_id = ? AND created_at BETWEEN ? AND ?", self.id, start_time, end_time]).length
begin
record = ClientStat.new(:client_id => self.id, :day => start_time.to_date,
:users => users, :user_badges => badges, :user_feats => feats)
record.save!
rescue => e
logger.error(e.message)
logger.error(e.backtrace)
end
end
# Authentication methods
def self.authenticate(username, password)
c=find(:first, :conditions=>["username = ?", username])
return nil if c.nil?
return c if Client.encrypt(password, c.salt)==c.hashed_password
nil
end
def password=(pass)
@password=pass
self.salt = Client.random_string(10) if !self.salt?
self.hashed_password = Client.encrypt(@password, self.salt)
end
# Mailer methods
def send_new_password
new_pass = Client.random_string(5)
self.password = self.password_confirmation = new_pass
if self.save
# Send the client email through a delayed job
ClientMailer.delay.send_forgot_password(self.email, self.username, new_pass)
return true
end
return false
end
def send_activation
if self.update_attributes(:activation_code => Client.generate_activation_code)
# Send the client email through a delayed job
ClientMailer.delay.send_activation(self.email, self.username, self.id, self.activation_code)
return true
end
return false
end
def send_email_change(old_email)
# Send the client email through a delayed job
ClientMailer.delay.send_changed_email(old_email, self.username, old_email, self.email)
return true
end
def update_email(new_email)
old_email = self.email
if self.update_attributes(:email => new_email, :activated => false)
if self.send_activation and self.send_email_change(old_email)
return true
end
end
return false
end
# Activation methods
def activate
return self.update_attributes(:activated => true)
end
def inactivate
return self.update_attributes(:activated => false)
end
# code generators
def self.generate_activation_code
Client.secure_digest(Time.now, (1..10).map{ rand.to_s })
end
def self.generate_api_key
Client.secure_digest(Time.now, (1..10).map{ rand.to_s })
end
protected
def password_required?
!password.blank?
end
def self.secure_digest(*args)
Digest::SHA1.hexdigest(args.flatten.join('--'))
end
def self.encrypt(password, salt)
Digest::SHA1.hexdigest(password+salt)
end
def self.random_string(len)
#generate a random password consisting of strings and digits
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
return newpass
end
end
|
# frozen_string_literal: true
# == Schema Information
#
# Table name: post_types
#
# id :bigint not null, primary key
# description_template :text
# name :string
# created_at :datetime not null
# updated_at :datetime not null
# user_id :bigint not null
#
# Indexes
#
# index_post_types_on_user_id (user_id)
#
# Foreign Keys
#
# fk_rails_... (user_id => users.id)
#
# rubocop:disable Rails/UniqueValidationWithoutIndex
class PostType < ApplicationRecord
extend Sortable
belongs_to :user
has_many :posts, dependent: :destroy
validates :name,
presence: true,
uniqueness: { scope: :user_id }
def self.merit_or_praise
raise_types = PostType.where('name ILIKE ? OR name ILIKE ?', '%merit%', '%praise%')
where('post_type IN ?', raise_types)
end
end
# rubocop:enable Rails/UniqueValidationWithoutIndex
|
# frozen_string_literal: true
require_relative "lib/hb_csv/version"
Gem::Specification.new do |spec|
spec.name = "hb-csv"
spec.version = HBCSV::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = ["Jesse Reiss", "Ryan Gerard", "Andrew Kiellor"]
spec.email = [nil, "kou@cozmixng.org"]
spec.summary = "CSV Reading and Writing"
spec.description = "The HBCSV library is a clone of CSV for Hummingbird."
spec.homepage = "https://github.com/Hummingbird-RegTech/hb-csv"
spec.license = "BSD-2-Clause"
spec.files = Dir.glob("lib/**/*.rb") + ["LICENSE.txt"]
spec.require_path = "lib"
spec.required_ruby_version = ">= 2.3.0"
spec.add_development_dependency "bundler"
spec.add_development_dependency "rake"
spec.add_development_dependency "benchmark-ips"
end
|
class AddNoticeToShippingMethods < ActiveRecord::Migration
def change
add_column :shipping_methods, :notice, :text
end
end
|
module ArchivesSpace
class EnumMerge
attr_reader :client, :enum, :old_value, :new_value
def initialize(client, enum, old_value, new_value)
@client = client
@enum = enum
@old_value = old_value
@new_value = new_value
end
def merge
result = client.get "config/enumerations"
enumerations = result.parsed
enumeration = enumerations.find { |e| e["name"] == enum }
raise "Unable to find enumeration #{enum}" unless enumeration
# match only literal on old_value
old_value_enum = enumeration["enumeration_values"].find {
|ev| ev["value"] == old_value
}
# for new_value it's ok to attach case insensitively (TODO: config?)
new_value_enum = enumeration["enumeration_values"].find {
|ev| ev["value"] == new_value or ev["value"] == new_value.downcase
}
raise "unable to find enumeration value #{old_value} in #{enumeration["values"]}" unless old_value_enum
raise "unable to find enumeration value #{new_value} in #{enumeration["values"]}" unless new_value_enum
raise "Cannot merge value #{old_value} into itself" if old_value_enum["value"] == new_value_enum["value"]
payload = { enum_uri: enumeration["uri"], from: old_value_enum["value"], to: new_value_enum["value"] }
result = client.post "config/enumerations/migration", payload
end
end
end |
class ChangeFormatDateRegistry < ActiveRecord::Migration
def change
change_column :registries, :last_registry, :datetime
end
end
|
class RemoveDefaultFromLocationOnPost < ActiveRecord::Migration
def change
change_column :posts, :location, :string
end
end
|
class List < ActiveRecord::Base
default_scope { order(index: :asc) }
end
|
class InstructionsController < ApplicationController
def index
@instructions = Instruction.all.inject({}) do |hash, instruction|
hash[instruction.id] = {
header: instruction.header,
content: instruction.content,
dog_name: instruction.dog.name
}
hash
end
end
def show
@instruction = Instruction.find(params[:id])
@user = current_session_user
@dog = @instruction.dog
end
def new
@instruction = Instruction.new
@dogs = current_session_user.dogs
@user = current_session_user
end
def create
instruction = Instruction.create(instruction_params)
if instruction.valid?
dog_username = Dog.find(params[:instruction][:dog_id]).username
redirect_to dog_path(dog_username)
else
flash[:errors] = instruction.errors.full_messages
redirect_to new_instruction_path
end
end
def edit
@instruction = Instruction.find(params[:id])
@dog = @instruction.dog
@dogs = Dog.all
@user = current_session_user
end
def update
instruction = Instruction.find(params[:id])
if instruction.update(instruction_params)
redirect_to instruction
else
flash[:errors] = instruction.errors.full_messages
redirect_to edit_instruction_path
end
end
private # ********************
def instruction_params
params.require(:instruction).permit(:header, :content, :dog_id)
end
end
|
class Mobilfunkgeraet < ActiveRecord::Base
attr_accessible :geraete_pin, :imei, :kommentar, :telefonnummer, :typ
validates :imei, presence: true, uniqueness: true
validates :geraete_pin, presence: true
validates :telefonnummer, presence: true
end
|
class Section::SettingWidget < Apotomo::Widget
responds_to_event :submit
def display(options = {})
@section = options[:section]
render
end
def submit(evt)
@section = Section.find evt[:id]
if @section.update_attributes(evt[:section])
trigger :updateName, :section => @section
end
end
end
|
class RemoveTimeslot < ActiveRecord::Migration
def change
remove_column :appointments, :time_slot
end
end
|
class Comment < ActiveRecord::Base
validates :content, presence: true
validates :user_id, presence: true
belongs_to :user
belongs_to :parent, class_name: "Comment"
has_many :replies, class_name: "Comment", foreign_key: :parent_id, dependent: :destroy
has_many :likes
private
def self.comment_parent
where(parent_id: nil)
end
end |
Rails.application.routes.draw do
get 'orders/new'
root 'static_pages#index'
get '/signup', to: 'users#new'
get '/addvehicle' ,to: 'vehicles#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/index', to: 'static_pages#index'
get '/autoFind',to: 'static_pages#autoFind'
post '/autoFind',to: 'static_pages#autoFind'
resources :users, :vehicles
resources :orders do
member do
post 'cancel_order'
post 'pay_order'
get 'return_car'
end
end
end
|
class AddMobileToStaff < ActiveRecord::Migration
def change
add_column :staffs, :mobile, :string
end
end
|
require 'spec_helper'
require 'will_paginate/finders/data_mapper'
require File.dirname(__FILE__) + '/data_mapper_test_connector'
require 'will_paginate'
describe WillPaginate::Finders::DataMapper do
it "should make #paginate available to DM resource classes" do
Animal.should respond_to(:paginate)
end
it "should paginate" do
Animal.expects(:all).with(:limit => 5, :offset => 0).returns([])
Animal.paginate(:page => 1, :per_page => 5)
end
it "should NOT to paginate_by_sql" do
Animal.should_not respond_to(:paginate_by_sql)
end
it "should support explicit :all argument" do
Animal.expects(:all).with(instance_of(Hash)).returns([])
Animal.paginate(:all, :page => nil)
end
it "should support conditional pagination" do
filtered_result = Animal.paginate(:all, :name => 'Dog', :page => nil)
filtered_result.size.should == 1
filtered_result.first.should == Animal.first(:name => 'Dog')
end
it "should leave extra parameters intact" do
Animal.expects(:all).with(:name => 'Dog', :limit => 4, :offset => 0 ).returns(Array.new(5))
Animal.expects(:count).with({:name => 'Dog'}).returns(1)
Animal.paginate :name => 'Dog', :page => 1, :per_page => 4
end
describe "counting" do
it "should ignore nil in :count parameter" do
lambda { Animal.paginate :page => nil, :count => nil }.should_not raise_error
end
it "should guess the total count" do
Animal.expects(:all).returns(Array.new(2))
Animal.expects(:count).never
result = Animal.paginate :page => 2, :per_page => 4
result.total_entries.should == 6
end
it "should guess that there are no records" do
Animal.expects(:all).returns([])
Animal.expects(:count).never
result = Animal.paginate :page => 1, :per_page => 4
result.total_entries.should == 0
end
end
end
|
module Square
# V1TransactionsApi
class V1TransactionsApi < BaseApi
# Provides summary information for a merchant's online store orders.
# @param [String] location_id Required parameter: The ID of the location to
# list online store orders for.
# @param [SortOrder] order Optional parameter: The order in which payments
# are listed in the response.
# @param [Integer] limit Optional parameter: The maximum number of payments
# to return in a single response. This value cannot exceed 200.
# @param [String] batch_token Optional parameter: A pagination cursor to
# retrieve the next set of results for your original query to the
# endpoint.
# @return [Array[V1Order] Hash] response from the API call
def v1_list_orders(location_id:,
order: nil,
limit: nil,
batch_token: nil)
warn 'Endpoint v1_list_orders in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/orders',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.query_param(new_parameter(order, key: 'order'))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(batch_token, key: 'batch_token'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create))
.is_response_array(true))
.execute
end
# Provides comprehensive information for a single online store order,
# including the order's history.
# @param [String] location_id Required parameter: The ID of the order's
# associated location.
# @param [String] order_id Required parameter: The order's Square-issued ID.
# You obtain this value from Order objects returned by the List Orders
# endpoint
# @return [V1Order Hash] response from the API call
def v1_retrieve_order(location_id:,
order_id:)
warn 'Endpoint v1_retrieve_order in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/orders/{order_id}',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.template_param(new_parameter(order_id, key: 'order_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Updates the details of an online store order. Every update you perform on
# an order corresponds to one of three actions:
# @param [String] location_id Required parameter: The ID of the order's
# associated location.
# @param [String] order_id Required parameter: The order's Square-issued ID.
# You obtain this value from Order objects returned by the List Orders
# endpoint
# @param [V1UpdateOrderRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [V1Order Hash] response from the API call
def v1_update_order(location_id:,
order_id:,
body:)
warn 'Endpoint v1_update_order in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::PUT,
'/v1/{location_id}/orders/{order_id}',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.template_param(new_parameter(order_id, key: 'order_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Provides summary information for all payments taken for a given
# Square account during a date range. Date ranges cannot exceed 1 year in
# length. See Date ranges for details of inclusive and exclusive dates.
# *Note**: Details for payments processed with Square Point of Sale while
# in offline mode may not be transmitted to Square for up to 72 hours.
# Offline payments have a `created_at` value that reflects the time the
# payment was originally processed, not the time it was subsequently
# transmitted to Square. Consequently, the ListPayments endpoint might
# list an offline payment chronologically between online payments that
# were seen in a previous request.
# @param [String] location_id Required parameter: The ID of the location to
# list payments for. If you specify me, this endpoint returns payments
# aggregated from all of the business's locations.
# @param [SortOrder] order Optional parameter: The order in which payments
# are listed in the response.
# @param [String] begin_time Optional parameter: The beginning of the
# requested reporting period, in ISO 8601 format. If this value is before
# January 1, 2013 (2013-01-01T00:00:00Z), this endpoint returns an error.
# Default value: The current time minus one year.
# @param [String] end_time Optional parameter: The end of the requested
# reporting period, in ISO 8601 format. If this value is more than one year
# greater than begin_time, this endpoint returns an error. Default value:
# The current time.
# @param [Integer] limit Optional parameter: The maximum number of payments
# to return in a single response. This value cannot exceed 200.
# @param [String] batch_token Optional parameter: A pagination cursor to
# retrieve the next set of results for your original query to the
# endpoint.
# @param [TrueClass | FalseClass] include_partial Optional parameter:
# Indicates whether or not to include partial payments in the response.
# Partial payments will have the tenders collected so far, but the
# itemizations will be empty until the payment is completed.
# @return [Array[V1Payment] Hash] response from the API call
def v1_list_payments(location_id:,
order: nil,
begin_time: nil,
end_time: nil,
limit: nil,
batch_token: nil,
include_partial: false)
warn 'Endpoint v1_list_payments in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/payments',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.query_param(new_parameter(order, key: 'order'))
.query_param(new_parameter(begin_time, key: 'begin_time'))
.query_param(new_parameter(end_time, key: 'end_time'))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(batch_token, key: 'batch_token'))
.query_param(new_parameter(include_partial, key: 'include_partial'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create))
.is_response_array(true))
.execute
end
# Provides comprehensive information for a single payment.
# @param [String] location_id Required parameter: The ID of the payment's
# associated location.
# @param [String] payment_id Required parameter: The Square-issued payment
# ID. payment_id comes from Payment objects returned by the List Payments
# endpoint, Settlement objects returned by the List Settlements endpoint, or
# Refund objects returned by the List Refunds endpoint.
# @return [V1Payment Hash] response from the API call
def v1_retrieve_payment(location_id:,
payment_id:)
warn 'Endpoint v1_retrieve_payment in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/payments/{payment_id}',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.template_param(new_parameter(payment_id, key: 'payment_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Provides the details for all refunds initiated by a merchant or any of the
# merchant's mobile staff during a date range. Date ranges cannot exceed one
# year in length.
# @param [String] location_id Required parameter: The ID of the location to
# list refunds for.
# @param [SortOrder] order Optional parameter: The order in which payments
# are listed in the response.
# @param [String] begin_time Optional parameter: The beginning of the
# requested reporting period, in ISO 8601 format. If this value is before
# January 1, 2013 (2013-01-01T00:00:00Z), this endpoint returns an error.
# Default value: The current time minus one year.
# @param [String] end_time Optional parameter: The end of the requested
# reporting period, in ISO 8601 format. If this value is more than one year
# greater than begin_time, this endpoint returns an error. Default value:
# The current time.
# @param [Integer] limit Optional parameter: The approximate number of
# refunds to return in a single response. Default: 100. Max: 200. Response
# may contain more results than the prescribed limit when refunds are made
# simultaneously to multiple tenders in a payment or when refunds are
# generated in an exchange to account for the value of returned goods.
# @param [String] batch_token Optional parameter: A pagination cursor to
# retrieve the next set of results for your original query to the
# endpoint.
# @return [Array[V1Refund] Hash] response from the API call
def v1_list_refunds(location_id:,
order: nil,
begin_time: nil,
end_time: nil,
limit: nil,
batch_token: nil)
warn 'Endpoint v1_list_refunds in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/refunds',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.query_param(new_parameter(order, key: 'order'))
.query_param(new_parameter(begin_time, key: 'begin_time'))
.query_param(new_parameter(end_time, key: 'end_time'))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(batch_token, key: 'batch_token'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create))
.is_response_array(true))
.execute
end
# Issues a refund for a previously processed payment. You must issue
# a refund within 60 days of the associated payment.
# You cannot issue a partial refund for a split tender payment. You must
# instead issue a full or partial refund for a particular tender, by
# providing the applicable tender id to the V1CreateRefund endpoint.
# Issuing a full refund for a split tender payment refunds all tenders
# associated with the payment.
# Issuing a refund for a card payment is not reversible. For development
# purposes, you can create fake cash payments in Square Point of Sale and
# refund them.
# @param [String] location_id Required parameter: The ID of the original
# payment's associated location.
# @param [V1CreateRefundRequest] body Required parameter: An object
# containing the fields to POST for the request. See the corresponding
# object definition for field details.
# @return [V1Refund Hash] response from the API call
def v1_create_refund(location_id:,
body:)
warn 'Endpoint v1_create_refund in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::POST,
'/v1/{location_id}/refunds',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'Content-Type'))
.body_param(new_parameter(body))
.header_param(new_parameter('application/json', key: 'accept'))
.body_serializer(proc do |param| param.to_json unless param.nil? end)
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
# Provides summary information for all deposits and withdrawals
# initiated by Square to a linked bank account during a date range. Date
# ranges cannot exceed one year in length.
# *Note**: the ListSettlements endpoint does not provide entry
# information.
# @param [String] location_id Required parameter: The ID of the location to
# list settlements for. If you specify me, this endpoint returns settlements
# aggregated from all of the business's locations.
# @param [SortOrder] order Optional parameter: The order in which
# settlements are listed in the response.
# @param [String] begin_time Optional parameter: The beginning of the
# requested reporting period, in ISO 8601 format. If this value is before
# January 1, 2013 (2013-01-01T00:00:00Z), this endpoint returns an error.
# Default value: The current time minus one year.
# @param [String] end_time Optional parameter: The end of the requested
# reporting period, in ISO 8601 format. If this value is more than one year
# greater than begin_time, this endpoint returns an error. Default value:
# The current time.
# @param [Integer] limit Optional parameter: The maximum number of
# settlements to return in a single response. This value cannot exceed
# 200.
# @param [V1ListSettlementsRequestStatus] status Optional parameter: Provide
# this parameter to retrieve only settlements with a particular status (SENT
# or FAILED).
# @param [String] batch_token Optional parameter: A pagination cursor to
# retrieve the next set of results for your original query to the
# endpoint.
# @return [Array[V1Settlement] Hash] response from the API call
def v1_list_settlements(location_id:,
order: nil,
begin_time: nil,
end_time: nil,
limit: nil,
status: nil,
batch_token: nil)
warn 'Endpoint v1_list_settlements in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/settlements',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.query_param(new_parameter(order, key: 'order'))
.query_param(new_parameter(begin_time, key: 'begin_time'))
.query_param(new_parameter(end_time, key: 'end_time'))
.query_param(new_parameter(limit, key: 'limit'))
.query_param(new_parameter(status, key: 'status'))
.query_param(new_parameter(batch_token, key: 'batch_token'))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create))
.is_response_array(true))
.execute
end
# Provides comprehensive information for a single settlement.
# The returned `Settlement` objects include an `entries` field that lists
# the transactions that contribute to the settlement total. Most
# settlement entries correspond to a payment payout, but settlement
# entries are also generated for less common events, like refunds, manual
# adjustments, or chargeback holds.
# Square initiates its regular deposits as indicated in the
# [Deposit Options with
# Square](https://squareup.com/help/us/en/article/3807)
# help article. Details for a regular deposit are usually not available
# from Connect API endpoints before 10 p.m. PST the same day.
# Square does not know when an initiated settlement **completes**, only
# whether it has failed. A completed settlement is typically reflected in
# a bank account within 3 business days, but in exceptional cases it may
# take longer.
# @param [String] location_id Required parameter: The ID of the
# settlements's associated location.
# @param [String] settlement_id Required parameter: The settlement's
# Square-issued ID. You obtain this value from Settlement objects returned
# by the List Settlements endpoint.
# @return [V1Settlement Hash] response from the API call
def v1_retrieve_settlement(location_id:,
settlement_id:)
warn 'Endpoint v1_retrieve_settlement in V1TransactionsApi is deprecated'
new_api_call_builder
.request(new_request_builder(HttpMethodEnum::GET,
'/v1/{location_id}/settlements/{settlement_id}',
'default')
.template_param(new_parameter(location_id, key: 'location_id')
.should_encode(true))
.template_param(new_parameter(settlement_id, key: 'settlement_id')
.should_encode(true))
.header_param(new_parameter('application/json', key: 'accept'))
.auth(Single.new('global')))
.response(new_response_handler
.deserializer(APIHelper.method(:json_deserialize))
.is_api_response(true)
.convertor(ApiResponse.method(:create)))
.execute
end
end
end
|
require 'spec_helper'
describe "historicos/new" do
before(:each) do
assign(:historico, stub_model(Historico,
:evento => "MyString",
:observacao => "MyString",
:data => "MyString",
:remessa => nil
).as_new_record)
end
it "renders new historico form" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "form[action=?][method=?]", historicos_path, "post" do
assert_select "input#historico_evento[name=?]", "historico[evento]"
assert_select "input#historico_observacao[name=?]", "historico[observacao]"
assert_select "input#historico_data[name=?]", "historico[data]"
assert_select "input#historico_remessa[name=?]", "historico[remessa]"
end
end
end
|
module Octonaut
desc "View your profile"
command :me do |c|
c.action do |global,options,args|
user = @client.user
print_user_table user
end
end
desc "View profile for a user"
arg_name 'login'
command [:user, :whois] do |c|
c.action do |global,options,args|
login = args.shift
begin
user = @client.user login
case user['type']
when 'Organization'
print_org_table user
else
print_user_table user
end
rescue Octokit::NotFound
puts "User or organization #{login} not found"
end
end
end
desc "View followers for a user"
arg_name 'login', :optional
command :followers do |c|
c.action do |global,options,args|
login = args.shift || @client.login
print_users @client.followers(login), options
end
end
desc "View who a user is following"
arg_name 'login', :optional
command :following do |c|
c.action do |global,options,args|
login = args.shift || @client.login
print_users @client.following(login), options
end
end
desc "Check to see if a user follows another"
arg_name 'target'
command :follows do |c|
c.action do |global,options,args|
target = args.shift
message = if @client.follows?(target)
"Yes, #{@client.login} follows #{target}."
else
"No, #{@client.login} does not follow #{target}."
end
puts message
end
end
desc "Follow a user"
arg_name 'target', :multiple
command :follow do |c|
c.action do |global,options,args|
targets = args
targets.each {|t| follow_user(t) }
end
end
desc "Unfollow a user"
arg_name 'target', :multiple
command :unfollow do |c|
c.action do |global,options,args|
targets = args
targets.each {|t| unfollow_user(t) }
end
end
def self.follow_user(target)
puts "Followed #{target}." if @client.follow(target)
end
def self.unfollow_user(target)
puts "Unfollowed #{target}." if @client.unfollow(target)
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery
helper_method :helper_method
def helper_method
raise "I will never ever be called!"
end
end
|
require 'rails_helper'
RSpec.describe Step, type: :model do
describe 'DB Columns' do
it {should have_db_column(:sequential_number).of_type :integer}
end
describe 'validations' do
it {should validate_presence_of :sequential_number}
end
describe 'belongs_to associations' do
it {should belong_to :project}
it {should belong_to :feature}
end
end
|
module Refinery
module Pages
class TestimonialsSectionPresenter < Refinery::Pages::CollectionPresenter
include ActiveSupport::Configurable
# A presenter which knows how to render a single testimonial
attr_accessor :output_buffer
config_accessor :item_class, :item_tag, :quote_includes_cite, :date_tag, :name_tag, :quote_tag, :cite_tag
self.item_class = :received_channel
self.item_tag = :li
self.date_tag = :p
self.name_tag = :p
self.quote_tag = :blockquote
self.cite_tag = :cite
self.quote_includes_cite = true
def initialize(page_part)
# return if page_part.nil?
super
self.fallback_html = ""
end
def content_html(can_use_fallback)
override_html.present? ? override_html : collection_markup()
end
private
def item_markup(item)
ic = item.respond_to?(item_class) ? item.send(item_class) : item_class
content_tag(item_tag.to_sym, id: item.id, class: ic) do
buffer = ActiveSupport::SafeBuffer.new
buffer << date_markup(item.received_date) << quote_markup(item.quote, item.name, item.job_title, item.company, item.website)
end
end
def date_markup(date)
content_tag(date_tag, date, class: "date")
end
def name_markup(name)
content_tag(name_tag, name, class: 'testimonial_name' )
end
def quote_markup(quote, name, job_title, company, website)
c = cite_markup(name, job_title, company, website)
if quote_includes_cite
content_tag(quote_tag) {
quote.html_safe << c
}
else
content_tag(quote_tag, quote.html_safe) << c
end
end
def cite_markup(name, job_title, company, website)
# combine job job_title, company, website (all optional)
# from original refinery-testimonial, restored to life
citation = [content_tag(:b, name), job_title, website_or_company(company, website) ].reject(&:blank?).join(", ").sub(/,\s/, ": ")
content_tag(cite_tag, citation.html_safe)
end
def website_or_company(company, website)
link = content_tag(:a, company.blank? ? website : company, href: website)
website.blank? ? company : link
end
def html_from_fallback(can_use_fallback)
fallback_html if fallback_html.present? && can_use_fallback
end
end
end
end
|
class Product < ActiveRecord::Base
belongs_to :company
has_many :product_reviews
validates :name, :price, :company_id, presence: true
end
|
class AnimalInfo::Scraper
def self.scrape_from_wikipedia(name)
html = get_html(name)
animal_name = html.search("h1#firstHeading").text
properties = { name: animal_name }
categories = ["Kingdom", "Phylum", "Class", "Order"]
html.search("table.infobox.biota tr").each do |table_row|
table_data = table_row.search("td")
if table_data.size == 2
category = table_data.first.text.strip.gsub(":", "")
if categories.include?(category)
if !table_data.last.search("b").empty?
category_info = table_data.last.search("b").text.strip
else
category_info = table_data.last.text.strip
end
category = "Klass" if category == "Class"
properties[category.downcase.to_sym] = category_info
end
end
end
properties[:url] = "https://en.wikipedia.org/wiki/#{name}"
properties
end
def self.get_html(name)
url = "https://en.wikipedia.org/wiki/#{name}"
Nokogiri::HTML(open(url))
end
end
|
class AddUploadAttemptOnSuccessfulUploadOnToAudits < ActiveRecord::Migration
def change
add_column :audits, :upload_attempt_on, :datetime
add_column :audits, :successful_upload_on, :datetime
end
end
|
$: << File.dirname(__FILE__) + '/../lib/'
require 'nabaztag/choreography'
require 'test/unit'
class ChoreographyTest < Test::Unit::TestCase
class Choreography < Nabaztag::Choreography
attr_reader :messages
end
def test_should_reproduce_api_example_2
ch = Choreography.new{
ear :left, 20, :forward
}
assert_equal ['0,motor,1,20,0,0'], ch.messages
end
def test_should_reproduce_api_example_3
ch = Choreography.new{
length 2 do
led :middle, 0, 238, 0
end
led :left, 250, 0, 0
led :middle, :off
}
assert_equal ['0,led,2,0,238,0','2,led,1,250,0,0','3,led,2,0,0,0'], ch.messages
end
def test_should_reproduce_api_example_4
ch = Choreography.new{
tempo 10
together 2 do
ear :left, 20, :forward
led :middle, 0, 238, 0
end
led :left, 250, 0, 0
led :middle, :off
}
assert_equal '10,0,motor,1,20,0,0,0,led,2,0,238,0,2,led,1,250,0,0,3,led,2,0,0,0', ch.build
end
end |
require 'dotenv'
Dotenv.load
puts "Using proxy: #{ENV['INSTAGRAM_SCRAPING_PROXY_HOST']}"
require "capybara"
require 'selenium/webdriver'
require 'capybara/dsl'
require 'site_prism'
$LOAD_PATH << File.expand_path("..", __FILE__)
require 'settings'
require 'page_objects/pages/instagram_page'
require 'page_objects/pages/explore_tags_page'
require 'page_objects/application'
require 'browse_helpers'
def read_from_file(filename)
full_path = "#{File.expand_path("..", __FILE__)}/#{filename}"
result = []
File.readlines(full_path).each do |line|
line.chomp!
result << line unless line.empty?
end
result
end
username = ARGV[0].chomp
hash_tag = ARGV[1].chomp
comments = nil
comments = read_from_file(ARGV[2].chomp) unless ARGV[2].nil?
puts "Email: #{username}"
puts "Hash Tag: #{hash_tag}"
ARGV.clear
puts "Please, give me your password to login to Instagram: "
password = gets.chomp
if password.empty?
puts "It cannot be blank"
exit 1
end
puts "Comments to be used: #{comments.inspect}" unless comments.nil?
Capybara.register_driver :firefox_with_proxy do |app|
proxy = "#{ENV['INSTAGRAM_SCRAPING_PROXY_HOST']}:#{ENV['INSTAGRAM_SCRAPING_PROXY_PORT']}"
profile = Selenium::WebDriver::Firefox::Profile.new
profile.proxy = Selenium::WebDriver::Proxy.new(
:http => proxy,
:ssl => proxy,
:socks_username => ENV['INSTAGRAM_SCRAPING_PROXY_USERNAME'],
:socks_password => ENV['INSTAGRAM_SCRAPING_PROXY_PASSWORD']
)
Capybara::Selenium::Driver.new(app, :profile => profile)
end
Capybara.default_driver = :firefox_with_proxy
$app = PageObjects::Application.new
$app.instagram.load
login(username, password)
any_results = search(hash_tag)
unless any_results
puts "No results"
exit(0)
end
sleep(2)
i = 1
next_post_button = true
comments_index = 0
while next_post_button
puts "going to post #{i}"
like_heart = $app.explore_tags.likes.first
if like_heart.nil?
puts "...no like heart found"
else
like_heart.click
unless comments.nil?
comment_input = $app.explore_tags.comments.first
if comment_input.nil?
puts "...no comment area found"
else
comment_input.set "#{comments[comments_index]}\n"
puts "...comment posted"
comments_index += 1
comments_index = 0 if comments_index == comments.size
end
end
end
sleep(3)
next_post_button = $app.explore_tags.next_post
unless next_post_button.nil?
next_post_button.click
i += 1
sleep(2)
end
end |
require 'yt/collections/base'
require 'yt/models/snippet'
module Yt
module Collections
# @private
class Snippets < Base
private
def attributes_for_new_item(data)
{data: data['snippet'], auth: @auth}
end
# @return [Hash] the parameters to submit to YouTube to get the
# snippet of a resource, for instance a channel.
# @see https://developers.google.com/youtube/v3/docs/channels#resource
def list_params
endpoint = @parent.kind.pluralize.camelize :lower
super.tap do |params|
params[:path] = "/youtube/v3/#{endpoint}"
params[:params] = {id: @parent.id, part: 'snippet'}
end
end
end
end
end |
require 'spec_helper'
describe Opendata::ListHelper, type: :helper, dbscope: :example do
describe ".render_page_list" do
context "without block" do
subject { helper.render_page_list }
before do
@cur_site = cms_site
create(:opendata_node_search_dataset)
@cur_part = create(:opendata_part_dataset)
@cur_node = create(:opendata_node_dataset)
@cur_path = @cur_node.filename
@item1 = create(:opendata_dataset, node: @cur_node)
@item2 = create(:opendata_dataset, node: @cur_node)
@item3 = create(:opendata_dataset, node: @cur_node)
@items = Opendata::Dataset.all
end
it do
is_expected.to include "<article class=\"item-#{@item1.basename.sub(/\..*/, "").dasherize} new \">"
is_expected.to include "<article class=\"item-#{@item2.basename.sub(/\..*/, "").dasherize} new \">"
is_expected.to include "<article class=\"item-#{@item3.basename.sub(/\..*/, "").dasherize} new \">"
end
end
context "with block" do
let(:now) { Time.zone.now }
subject do
helper.render_page_list { "現在の時刻は#{now}" }
end
before do
@cur_site = cms_site
create(:opendata_node_search_dataset)
@cur_part = create(:opendata_part_dataset)
@cur_node = create(:opendata_node_dataset)
@cur_path = @cur_node.filename
@item1 = create(:opendata_dataset, node: @cur_node)
@item2 = create(:opendata_dataset, node: @cur_node)
@item3 = create(:opendata_dataset, node: @cur_node)
@items = Opendata::Dataset.all
end
it do
is_expected.to include "現在の時刻は#{now}"
end
end
end
end
|
class CreateCustomers < ActiveRecord::Migration
def change
create_table :customers do |t|
t.string :nombres
t.string :ap_paterno
t.string :ap_materno
t.string :sexo
t.string :tipo_doc
t.string :nro_doc
t.string :email
t.string :password
t.date :fch_nacimiento
t.string :telefono
t.timestamps
end
end
end
|
# frozen_string_literal: true
class Protocol < ApplicationRecord
belongs_to :card
belongs_to :expert
enum type_of_inspection: { first_visit: 0, second_visit: 1 }
validates :type_of_inspection, :diagnosis, presence: true
end
|
require 'fileutils'
require 'tempfile'
module Vfs
module Drivers
class Local
class Writer
def initialize out; @out = out end
def write data
@out.write data
end
end
DEFAULT_BUFFER = 1000 * 1024
def initialize options = {}
options = options.clone
@root = options.delete(:root) || ''
raise "invalid options #{options}" unless options.empty?
end
def open &block
block.call self if block
end
def close; end
attr_writer :buffer
def buffer
@buffer || DEFAULT_BUFFER
end
# Attributes.
def attributes path
path = with_root path
stat = ::File.stat path
attrs = {}
attrs[:file] = !!stat.file?
attrs[:dir] = !!stat.directory?
# attributes special for file system
attrs[:created_at] = stat.ctime
attrs[:updated_at] = stat.mtime
attrs[:size] = stat.size if attrs[:file]
attrs
rescue Errno::ENOTDIR
nil
rescue Errno::ENOENT
nil
end
def set_attributes path, attrs
# TODO2 set attributes.
not_implemented
end
# File.
def read_file path, &block
path = with_root path
::File.open path, 'r' do |is|
while buff = is.gets(self.buffer || DEFAULT_BUFFER)
block.call buff
end
end
end
def write_file original_path, append, &block
path = with_root original_path
option = append ? 'a' : 'w'
::File.open path, "#{option}b" do |out|
block.call Writer.new(out)
end
end
def delete_file path
path = with_root path
::File.delete path
end
# def move_file from, to
# FileUtils.mv from, to
# end
# Dir.
def create_dir path
path = with_root path
::Dir.mkdir path
end
def delete_dir original_path
path = with_root original_path
::FileUtils.rm_r path
end
def each_entry path, query, &block
path = with_root path
if query
path_with_trailing_slash = path == '/' ? path : "#{path}/"
::Dir["#{path_with_trailing_slash}#{query}"].each do |absolute_path|
name = absolute_path.sub path_with_trailing_slash, ''
block.call name, ->{::File.directory?(absolute_path) ? :dir : :file}
end
else
::Dir.foreach path do |name|
next if name == '.' or name == '..'
block.call name, ->{::File.directory?("#{path}/#{name}") ? :dir : :file}
end
end
end
# def efficient_dir_copy from, to, override
# return false if override # FileUtils.cp_r doesn't support this behaviour
#
# from.driver.open_fs do |from_fs|
# to.driver.open_fs do |to_fs|
# if from_fs.local? and to_fs.local?
# FileUtils.cp_r from.path, to.path
# true
# else
# false
# end
# end
# end
# end
# Other.
def local?; true end
def tmp &block
path = "/tmp/#{rand(10**6)}"
if block
begin
::FileUtils.mkdir_p with_root(path)
block.call path
ensure
::FileUtils.rm_r with_root(path) if ::File.exist? with_root(path)
end
else
::FileUtils.mkdir_p with_root(path)
path
end
end
def to_s; '' end
protected
def root
@root || raise('root not defined!')
end
def with_root path
path == '/' ? root : root + path
end
end
end
end |
class AddSentColumnToApproval < ActiveRecord::Migration[5.0]
def change
add_column :approvals, :sent, :boolean, default: false
end
end
|
require 'test_helper'
class PedidolineasControllerTest < ActionController::TestCase
setup do
@pedidolinea = pedidolineas(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:pedidolineas)
end
test "should get new" do
get :new
assert_response :success
end
test "should create pedidolinea" do
assert_difference('Pedidolinea.count') do
post :create, pedidolinea: { cantidad: @pedidolinea.cantidad, imagen: @pedidolinea.imagen, pedido_id: @pedidolinea.pedido_id, precio: @pedidolinea.precio, product_id: @pedidolinea.product_id, product_value: @pedidolinea.product_value, producto: @pedidolinea.producto, total: @pedidolinea.total }
end
assert_redirected_to pedidolinea_path(assigns(:pedidolinea))
end
test "should show pedidolinea" do
get :show, id: @pedidolinea
assert_response :success
end
test "should get edit" do
get :edit, id: @pedidolinea
assert_response :success
end
test "should update pedidolinea" do
patch :update, id: @pedidolinea, pedidolinea: { cantidad: @pedidolinea.cantidad, imagen: @pedidolinea.imagen, pedido_id: @pedidolinea.pedido_id, precio: @pedidolinea.precio, product_id: @pedidolinea.product_id, product_value: @pedidolinea.product_value, producto: @pedidolinea.producto, total: @pedidolinea.total }
assert_redirected_to pedidolinea_path(assigns(:pedidolinea))
end
test "should destroy pedidolinea" do
assert_difference('Pedidolinea.count', -1) do
delete :destroy, id: @pedidolinea
end
assert_redirected_to pedidolineas_path
end
end
|
#!/usr/bin/env ruby
# minitest_test2spec
# 20180729
# 0.6.1
# Changes since 0.5:
# 1. Not opening each file multiple times now.
# 2. Change of name: /minitest_assertion2spec/minitest_test2spec/.
# 0/1
# 3. - require 'fileutils', since need of it was gone as of 0.6.0.
# 4. /test\/assert_style.rb/test\/test_style.rb/.
# Todo:
# 1. Don't use Files (or similar approaches) because each file is being opened multiple times; which is ironic given that I started writing this for converting Files' tests. Done as of 0.6 after pinching the structure from should2expect.
class MiniTestFile
attr_accessor :contents
attr_accessor :minitest_filename
def initialize(minitest_filename)
@minitest_filename = minitest_filename
@contents = File.read(minitest_filename)
end
def transform
class2describe
setup2before
teardown2after
test2describeit
assert_equal2must_equal
assert_matcher2must_match
assert_nil2must_be_nil
write
end
private
def class2describe
contents.gsub!(/class +TC(_*)(.+?)_(.+) +< +MiniTest::Test/, "describe \"\\2 \\3\" do")
end
def setup2before
contents.gsub!(/def setup/, 'before do')
end
def teardown2after
contents.gsub!(/def teardown/, 'after do')
end
def test2describeit
existing_contents = contents
new_contents = ''
in_test_method = false
test_method_pattern = /^ *def +test_(.+?)$/
existing_contents.each_line do |line|
if in_test_method
if line =~ /end$/
in_test_method = false
new_contents << ' end' + "\n"
new_contents << ' end' + "\n"
else
new_contents << ' ' + line
end
elsif line =~ test_method_pattern
in_test_method = true
md = line.match(test_method_pattern)
new_contents << ' describe ' + '"' + md[1].gsub('_', ' ') + '"' + ' do' + "\n"
new_contents << ' it "works" do' + "\n"
else
new_contents << line
end
end
self.contents = new_contents
end
def assert_equal2must_equal
contents.gsub!(/assert_equal +(.+), +(.+)/, "expect\(\\2\).must_equal \\1")
end
def assert_matcher2must_match
contents.gsub!(/assert +(.+?) +=\~ +(.+)/, "expect\(\\1\).must_match \\2")
end
def assert_nil2must_be_nil
contents.gsub!(/assert_nil +(.+)/, "expect\(\\1\).must_be_nil")
end
def write
File.write(minitest_filename, contents)
end
end # class MiniTestFile
def input_filenames
if ARGV[0]
if File.directory?(ARGV[0])
Dir["#{ARGV[0]}/**/*.rb"]
else
Dir[ARGV[0]]
end
else
Dir['*.rb']
end
end
def minitest_filenames
input_filenames.reject do |input_filename|
File.directory?(input_filename)
end
end
def main
minitest_filenames.each do |minitest_filename|
MiniTestFile.new(minitest_filename).transform
end
end
main if __FILE__ == $0
|
class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :set_post
before_action :set_comment, only: [:edit, :update, :destroy]
# GET posts/1/comments/1/edit
def edit
authorize @comment
end
# POST posts/1/comments
# POST posts/1/comments.json
def create
@comment = @post.comments.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
format.html { redirect_to [@post.topic, @post], notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: @comment }
else
format.html { redirect_to [@post.topic, @post], notice: 'Error. Comment failed to save.'}
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT posts/1/comments/1
# PATCH/PUT posts/1/comments/1.json
def update
authorize @comment
respond_to do |format|
if @comment.update(comment_params)
format.html { redirect_to [@post.topic, @post], notice: 'Commment was successfully updated.' }
format.json { render :show, status: :ok, location: @comment }
else
format.html { render :edit }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
# DELETE posts/1/comments/1
# DELETE posts/1/comments/1.json
def destroy
authorize @comment
@comment.destroy
respond_to do |format|
format.html { redirect_to [@post.topic, @post], notice: 'Comment was successfully deleted.' }
format.json { head :no_content }
end
end
private
def set_post
@post = Post.find(params[:post_id])
end
def set_comment
@comment = @post.comments.find(params[:id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
|
module SitescanCommon
class AttributeNumber < ActiveRecord::Base
self.table_name = :attribute_numbers
has_one :product_attribute, as: :value,
class_name: SitescanCommon::ProductAttribute
after_save :product_reindex
protected
def product_reindex
product_attribute.product_reindex if product_attribute
end
end
end
|
# frozen_string_literal: true
class DashboardController < ApplicationController
before_action :authenticate_user!
def index
@posts = Post.where(postable_type: 'User').of_followed_users(current_user.following).order('created_at DESC').page params[:page]
@post = current_user.posts.build
end
def search
unless params[:username]
flash[:danger] = 'No search as given'
redirect_to root_path
end
# @result = User.search_name(params[:username].downcase)
# puts '__________________________________________________________________'
# puts params[:username]
# puts @result
end
end
|
class Movie < ActiveRecord::Base
has_many :nominations
has_many :nominees, through: :nominations
end
|
require 'spec_helper'
describe UsersController do
let(:user) { users(:owner) }
before do
log_in user
end
describe "#index" do
it_behaves_like "an action that requires authentication", :get, :index
it "succeeds" do
get :index
response.code.should == "200"
end
it "shows list of users" do
get :index
decoded_response.length.should == User.count
end
it_behaves_like "a paginated list"
describe "sorting" do
it "sorts by first name" do
get :index
decoded_response.first.first_name.should <= decoded_response.second.first_name
end
context "with a recognized sort order" do
it "respects the sort order" do
get :index, :order => "last_name"
decoded_response.first.last_name.downcase.should <= decoded_response.second.last_name.downcase
end
end
end
describe "pagination" do
it "paginates the collection" do
get :index, :page => 1, :per_page => 2
decoded_response.length.should == 2
end
it "defaults to page one" do
get :index, :per_page => 2
decoded_response.length.should == 2
end
it "accepts a page parameter" do
get :index, :page => 2, :per_page => 2
decoded_response.length.should == 2
decoded_response.first.username.should == User.order(:first_name)[2].username
end
it "defaults the per_page to fifty" do
get :index
request.params[:per_page].should == 50
end
end
generate_fixture "userSet.json" do
get :index
end
end
describe "#create" do
let(:params) {
{:username => "another_user", :password => "secret", :first_name => "joe",
:last_name => "user", :email => "joe@chorus.com", :title => "Data Scientist",
:dept => "bureau of bureaucracy", :notes => "poor personal hygiene", :admin => true}
}
it_behaves_like "an action that requires authentication", :post, :create
context "when creator is not admin" do
let(:user) { users(:restricted_user) }
it "should refuse" do
post :create, params
response.should be_forbidden
end
end
context "when creator is admin" do
let(:user) { users(:admin) }
before do
post :create, params
end
it "should succeed" do
response.code.should == "201"
end
it "should create a user" do
User.find_by_username(params[:username]).should be_present
end
it "should make a user an admin" do
User.find_by_username(params[:username]).admin.should be_true
end
it "should return the user's fields except password" do
params.each do |key, value|
key = key.to_s
decoded_response[key].should == value unless key == "password"
end
end
it "should refuse invalid data" do
post :create
response.code.should == "422"
end
it "makes a UserAdded event" do
event = Events::UserAdded.last
event.new_user.should == User.find_by_username(params[:username])
event.actor.should == user
end
generate_fixture "userWithErrors.json" do
post :create
end
end
end
describe "#update" do
let(:other_user) { users(:no_collaborators) }
let(:admin) { users(:admin) }
let(:non_admin) { users(:owner) }
it_behaves_like "an action that requires authentication", :put, :update
context "when logged in as an admin" do
before do
log_in admin
end
context "with a valid user id" do
it "responds with the updated user" do
put :update, :id => other_user.to_param, :admin => "true"
response.code.should == "200"
decoded_response.admin.should == true
end
it "allows making someone an admin" do
put :update, :id => other_user.to_param, :admin => "true"
other_user.reload.should be_admin
end
it "allows an admin to remove their own privileges, if there are other admins" do
put :update, :id => admin.to_param, :admin => "false"
response.code.should == "200"
decoded_response.admin.should == false
end
it "does not allow an admin to remove their own privileges if there are no other admins" do
users(:evil_admin).delete
put :update, :id => admin.to_param, :admin => "false"
response.code.should == "200"
decoded_response.admin.should == true
end
it "updates other attributes" do
put :update, :id => other_user.to_param, :first_name => "updated"
decoded_response.first_name.should == "updated"
end
end
context "with an invalid user id" do
it "returns not found" do
put :update, :id => 'bogus', :first_name => "updated"
response.should be_not_found
end
end
end
context "when the current user is not an admin" do
before do
log_in non_admin
end
it "allows the user to edit their own profile" do
expect {
put :update, :id => non_admin.to_param, :first_name => "updated"
}.to_not change { non_admin.reload.last_name }
decoded_response.first_name.should == "updated"
end
it "does not allow non-admins to make themselves an admin" do
put :update, :id => non_admin.to_param, :admin => "true"
non_admin.reload.should_not be_admin
end
it "does not allow non-admins to update other users" do
expect {
put :update, :id => other_user.to_param, :first_name => "updated"
}.to_not change { other_user.reload.first_name }
response.code.should == "404"
end
it "lets users change their own password" do
put :update, :id => non_admin.to_param, :password => '987654'
response.code.should == "200"
user = User.find(non_admin.to_param)
user.password_digest.should == Digest::SHA256.hexdigest("987654" + user.password_salt)
end
end
end
describe "#show" do
let(:user) { users(:owner) }
let(:other_user) { users(:the_collaborator) }
before do
log_in user
end
it_behaves_like "an action that requires authentication", :get, :show
context "with a valid user id" do
it "succeeds" do
get :show, :id => other_user.to_param
response.should be_success
end
it "presents the user" do
mock.proxy(controller).present(other_user)
get :show, :id => other_user.to_param
end
end
context "with an invalid user id" do
it "returns not found" do
get :show, :id => 'bogus'
response.should be_not_found
end
end
generate_fixture "user.json" do
get :show, :id => other_user.to_param
end
end
describe "#destroy" do
context "admin" do
before do
log_in users(:admin)
end
context "user with no instances or workspaces" do
let(:user) { users(:the_collaborator) }
before do
delete :destroy, :id => user.id
end
it "should succeed" do
response.code.should == "200"
end
it "should respond with valid json" do
lambda { JSON.parse(response.body) }.should_not raise_error
end
it "should delete the user" do
deleted_user = User.find_with_destroyed(user.id)
deleted_user.deleted_at.should_not be_nil
end
end
context "user owns an instance" do
let(:user) { users(:the_collaborator) }
before do
user.gpdb_instances << gpdb_instances(:default)
delete :destroy, :id => user.id
end
it "should fail" do
response.code.should == "422"
end
it "should not delete the user" do
live_user = User.find_with_destroyed(user.id)
live_user.deleted_at.should be_nil
end
end
context "user owns a workspace" do
let(:user) { users(:the_collaborator) }
before do
user.owned_workspaces << workspaces(:public)
delete :destroy, :id => user.id
end
it "should fail" do
response.code.should == "422"
end
it "should not delete the user" do
live_user = User.find_with_destroyed(user.id)
live_user.deleted_at.should be_nil
end
end
end
context "non-admin" do
let(:user) { users(:the_collaborator) }
before(:each) do
log_in users(:owner)
delete :destroy, :id => user.id
end
it "should not succeed" do
response.code.should == "403"
end
it "should not delete the user" do
live_user = User.find_with_destroyed(user.id)
live_user.deleted_at.should be_nil
end
end
context "admin trying to delete himself" do
let(:admin) { users(:admin) }
before do
log_in admin
delete :destroy, :id => admin.id
end
it "should not succeed" do
response.code.should == "403"
end
end
end
describe "#ldap" do
before do
@user_attributes = {:username => "testguy", :first_name => "Test", :last_name => "Guy", :title => "Big Kahuna", :dept => "Greenery", :email => "testguy@example.com"}
stub(LdapClient).search.with_any_args { [@user_attributes] }
end
it_behaves_like "an action that requires authentication", :get, :ldap
context "as an admin" do
before(:each) do
log_in users(:admin)
end
it "returns the set of matching users" do
get :ldap, :username => "foo"
response.should be_success
hash = response.decoded_body[:response].first
@user_attributes.keys.each do |key|
hash[key].should == @user_attributes[key]
end
end
end
context "as a non-admin" do
before(:each) do
log_in users(:owner)
end
it "returns unauthorized" do
get :ldap, :username => "foo"
response.code.should == "403"
end
end
end
end
|
describe JWK::ECKey do
let(:private_jwk) do
File.read('spec/support/ec_private.json')
end
let(:public_jwk) do
File.read('spec/support/ec_public.json')
end
let(:private_pem) do
File.read('spec/support/ec_private.pem')
end
describe '#initialize' do
it 'raises with invalid parameters' do
expect { JWK::Key.from_json('{"kty":"EC","crv":"P-256"}') }.to raise_error(JWK::InvalidKey)
end
end
describe '#to_pem' do
it 'converts private keys to the right format' do
key = JWK::Key.from_json(private_jwk)
expect(key.to_pem).to eq private_pem
end
it 'raises with public keys' do
key = JWK::Key.from_json(public_jwk)
expect { key.to_pem }.to raise_error NotImplementedError
end
end
describe '#to_s' do
it 'converts to pem' do
key = JWK::Key.from_json(private_jwk)
expect(key.to_s).to eq(key.to_pem)
end
end
describe '#to_openssl_key' do
it 'converts the private key to an openssl object' do
key = JWK::Key.from_json(private_jwk)
begin
expect(key.to_openssl_key).to be_a OpenSSL::PKey::EC
rescue Exception => e
# This is expected to fail on old jRuby versions
raise e unless defined?(JRUBY_VERSION)
end
end
it 'converts the public keys to an openssl point' do
key = JWK::Key.from_json(public_jwk)
begin
expect(key.to_openssl_key).to be_a OpenSSL::PKey::EC::Point
rescue Exception => e
# This is expected to fail on old jRuby versions
raise e unless defined?(JRUBY_VERSION)
end
end
# See: http://blogs.adobe.com/security/2017/03/critical-vulnerability-uncovered-in-json-encryption.html
# See: https://github.com/asanso/jwe-sender/blob/master/jwe-sender.js
it 'is protected against Invalid Curve Attack' do
k1 = {
'kty' => 'EC',
'x' => 'WJiccv00-OX6udOeWKfiRhZzzkoAnfG9JOIDprQYpH8', 'y' => 'tAjB2i8hs-7i6GLRcgMTtCoPbybmoPRWhS9qUBf2ldc',
'crv' => 'P-256'
}.to_json
k2 = {
'kty' => 'EC',
'x' => 'XOXGQ9_6QCvBg3u8vCI-UdBvICAEcNNBrfqd7tG7oQ4', 'y' => 'hQoWNotnNzKlwiCneJkLIqDnTNw7IsdBC53VUqVjVJc',
'crv' => 'P-256'
}.to_json
jwk1 = JWK::Key.from_json(k1)
jwk2 = JWK::Key.from_json(k2)
begin
expect { jwk1.to_openssl_key }.to raise_error(OpenSSL::PKey::EC::Point::Error)
expect { jwk2.to_openssl_key }.to raise_error(OpenSSL::PKey::EC::Point::Error)
rescue NameError => e
# This is expected to fail on old jRuby versions
# Not because it's unsafe, but because EC were not implemented.
raise e unless defined?(JRUBY_VERSION)
end
end
end
describe '#to_json' do
it 'responds with the JWK JSON key' do
key = JWK::Key.from_json(private_jwk)
expect(JSON.parse(key.to_json)).to eq JSON.parse(private_jwk)
end
end
describe '#kty' do
it 'equals EC' do
key = JWK::Key.from_json(private_jwk)
expect(key.kty).to eq 'EC'
end
end
describe '#public?' do
it 'is true' do
key = JWK::Key.from_json(private_jwk)
expect(key.public?).to be_truthy
end
end
describe '#private?' do
it 'is true for private keys' do
key = JWK::Key.from_json(private_jwk)
expect(key.private?).to be_truthy
end
it 'is false for public keys' do
key = JWK::Key.from_json(public_jwk)
expect(key.private?).to be_falsey
end
end
end
|
require 'rails_helper'
RSpec.describe Answer, type: :model do
it_behaves_like 'linkable'
it_behaves_like 'votable'
it_behaves_like 'commentable'
describe 'associations' do
it { should belong_to(:question) }
it { should belong_to(:user) }
it 'have many attached files' do
expect(Answer.new.files).to be_an_instance_of(ActiveStorage::Attached::Many)
end
end
describe 'scopes' do
let!(:question) { create(:question) }
let!(:answer1) { create(:answer, question: question) }
let!(:answer2) { create(:answer, :best_answer, question: question) }
let!(:answer3) { create(:answer, question: question) }
context 'default scope by best: :desc, created_at: :asc' do
subject { question.answers.to_a }
it { is_expected.to match_array [answer2, answer1, answer3] }
end
end
describe 'validations' do
context '#body' do
it { should validate_presence_of :body }
end
context '#best' do
let!(:question) { create(:question) }
let!(:answer1) { create(:answer, :best_answer, question: question) }
context 'existing best answer' do
subject { answer1 }
it { should validate_uniqueness_of(:best).scoped_to(:question_id) }
end
context 'new best answer' do
subject { build(:answer, best: true, question: question) }
it { should_not validate_uniqueness_of(:best).scoped_to(:question_id) }
end
end
end
describe 'methods' do
context '#mark_as_best!' do
context 'change answer attributes' do
let!(:question) { create(:question) }
let!(:best_answer) { create(:answer, :best_answer, question: question) }
let!(:ordinary_answer) { create(:answer, question: question) }
context 'mark ordinary answer as best' do
before { ordinary_answer.mark_as_best! }
context 'ordinary_answer' do
subject { ordinary_answer }
it { is_expected.to be_best }
end
context 'best_answer' do
before { best_answer.reload }
subject { best_answer }
it { is_expected.not_to be_best }
end
end
context 'mark best answer repeatedly' do
before { best_answer.mark_as_best! }
context 'best_answer' do
subject { best_answer }
it { is_expected.to be_best }
end
context 'ordinary_answer' do
subject { ordinary_answer }
it { is_expected.not_to be_best }
end
end
end
context 'change reward attributes' do
let!(:question) { create(:question) }
let!(:answer) { create(:answer, question: question) }
context 'change reward user if reward present' do
let!(:reward) { create(:reward, question: question, user: nil) }
before { answer.mark_as_best! }
subject { reward.user }
it { is_expected.to eq answer.user }
end
context 'does not change reward user if reward does not present' do
before { answer.mark_as_best! }
subject { question.reward }
it { is_expected.to be_nil }
end
end
end
end
end
|
class Relationship < ActiveRecord::Base
<<<<<<< HEAD
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
=======
belongs_to :follower, class_name: "User"
belongs_to :followed, class_name: "User"
validates :follower_id, presence: true
validates :followed_id, presence: true
>>>>>>> 7a4ab8fb42ad8330c565974e3561a9714f3594ba
end
|
class DnsRecord < ApplicationRecord
has_many :dns_record_hostnames
has_many :hostnames, through: :dns_record_hostnames
accepts_nested_attributes_for :dns_record_hostnames
def hostnames=(s)
hostname_array = s.to_s.split(',').map(&:strip)
hostname_array.each do |hostname|
hostnames << Hostname.where(hostname: hostname).first_or_create
end
end
def self.to_p
all.map do |item|
{
id: item.id,
ip: item.ip
}
end
end
end
|
class MangasController < ApplicationController
before_action :get_manga, only: [:show]
def index
@mangas = Manga.order_manga.paginate page: params[:page], per_page: Settings.mangas.page
@categories = Category.order(:name)
if params[:q].present?
@q = Manga.search(params[:q])
@mangas = @q.result(distinct: true).paginate page: params[:page], per_page: Settings.mangas.page
if params[:scope].present?
check_scope.search(params[:q]).result(distinct: true)
elsif params[:search].present?
@mangas = @q.search(name_cont: params[:search]).result(distinct: true).paginate page: params[:page], per_page: Settings.mangas.page
if params[:scope].present?
check_scope.search(params[:q]).search(name_cont: params[:search]).result(distinct: true)
end
end
elsif params[:search].present?
@mangas = Manga.search(name_cont: params[:search]).result.paginate page: params[:page], per_page: Settings.mangas.page
if params[:scope].present?
check_scope.search(name_cont: params[:search]).result
end
else
if params[:scope].present?
check_scope
end
end
end
def show
@chapters = @manga.chapters.reverse
@authors = @manga.authors.all
@categories = @manga.categories.order(:name)
@supports = Supports::Manga.new @manga
@comment = Comment.new
@comments = @manga.comments.hash_tree
Manga.increment_counter(:number_of_read, @manga.id)
end
private
def get_manga
@manga = Manga.friendly.find(params[:id])
redirect_to root_url unless @manga
end
def check_scope
@mangas = case params[:scope]
when Settings.mangas.most_view
Manga.most_view.paginate page: params[:page], per_page: Settings.mangas.page
when Settings.mangas.top_rate
Manga.top_rate.paginate page: params[:page], per_page: Settings.mangas.page
when Settings.mangas.finished
Manga.finished.order(:name).paginate page: params[:page], per_page: Settings.mangas.page
when Settings.mangas.not_finished
Manga.not_finished.order(:name).paginate page: params[:page], per_page: Settings.mangas.page
when Settings.mangas.most_followed
Manga.most_followed.paginate page: params[:page], per_page: Settings.mangas.page
when Settings.mangas.by_week
Manga.hot_manga_by_time(Settings.mangas.time_limit.days).paginate page: params[:page], per_page: Settings.mangas.page
when Settings.mangas.by_month
Manga.hot_manga_by_time(1.month).paginate page: params[:page], per_page: Settings.mangas.page
else
Manga.order_manga.paginate page: params[:page], per_page: Settings.mangas.page
end
end
end
|
class CreateJournalEntries < ActiveRecord::Migration[5.0]
def change
create_table :journal_entries do |t|
t.text :gratitude
t.text :motivation
t.text :affirmation
t.text :success
t.text :lesson
t.references :user, foreign_key: true
t.timestamps
end
end
end
|
class AddSuppressionsAndDataFileToSegments < ActiveRecord::Migration
def change
add_column :segments, :suppressions, :string
add_column :segments, :data_file, :string
end
end
|
class Theme
attr_accessor :name, :author, :version, :url, :about
attr_reader :path
def initialize(theme = nil)
if theme
@path = File.join(Merb.dir_for(:themes), theme)
manifest = YAML::load_file(File.join(path, 'manifest.yml'))
manifest.each_pair do |k, v|
instance_variable_set("@#{k}", v)
end
end
end
def id
name
end
def destroy
FileUtils.rm_rf(path)
end
class << self
def all
if File.exists?(Merb.dir_for(:themes))
# Get every file in themes, remove ".", ".." and regular files and create a Theme object for everything else
@themes = Dir.open(Merb.dir_for(:themes)).
reject { |file| ['.', '..'].include?(file) }.
select { |file| File.directory?(File.join(Merb.dir_for(:themes), file)) }.
map { |file| Theme.new(file) }
else
@themes = []
end
end
def get(theme)
path = File.join(Merb.dir_for(:themes), theme)
if File.exists?(path)
return Theme.new(theme)
else
raise "Theme not found"
end
end
def install(url)
# Get manifest
manifest = YAML::load(Net::HTTP.get(URI.parse(url + ".yml")))
# Target
path = File.join(Merb.dir_for(:themes), manifest['name'])
# Clean up
FileUtils.rm_rf(path)
Dir.mkdir(path)
# Download the package and untgz
package = Net::HTTP.get(URI.parse(url + ".tgz"))
Archive::Tar::Minitar.unpack(Zlib::GzipReader.new(StringIO.new(package)), path)
# Grab metadata from manifest
new(manifest['name'])
end
end
end |
#!/usr/bin/env ruby
require 'loggz'
example = Loggz.new
#configuration
example.redis_ip = "localhost"
example.redis_password = ""
example.redis_port = 6379
#display verbose output
example.verbose = true
#path to where the file is located(ie /mnt/nfs/Edgecast) It MUST have a trailing slash
example.file_path = "/path/to/where/the/logs/are/"
#this will determine what keystore to send to reddis based on the first few matching characters
example.file_type_flag = "example"
#keystore is what is stored in redis according to the file type being parsed
example.keystore = "example_key"
#if the first line contains data about the log, then skip it
example.skip_first_line=true
#make sure the next admin who checks out this system process knows where it is and how to remove it from startup
puts "initiating /usr/sbin/loggz_" + example.file_type_flag + ".rb process.\n This takes the logs from the cdn folder:" + example.file_path + "\n"
puts "and moves them to the redis server " + example.redis_ip + "\n"
puts "If you need to remove this process from startup,\nedit the entry from /etc/init.d/before.local\n"
#run process
Process.daemon
example.sendtoredis
|
class SurveyAssignments < ActiveRecord::Base
attr_accessible :assigned_to, :user_id
belongs_to :survey
belongs_to :user
belongs_to :assignee, foreign_key: :assigned_to, class_name: 'User'
end
|
class AddNewFieldsToMpoints < ActiveRecord::Migration[5.0]
def change
add_column :mpoints, :messtation, :string
add_column :mpoints, :meconname, :string
add_column :mpoints, :clsstation, :string
add_column :mpoints, :clconname, :string
add_column :mpoints, :voltcl, :string
add_column :mpoints, :metertype, :string
add_column :mpoints, :meternum, :integer
add_column :mpoints, :koeftt, :string
add_column :mpoints, :koeftn, :string
add_column :mpoints, :koefcalc, :integer
end
end
|
class UserController < ApplicationController
before_filter :is_member_of, :only => [:show, :list, :destroy, :remove_user_from_submission]
skip_before_filter :check_submiss_status
layout "submission"
# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
# verify :method => :post, :only => [ :destroy, :create, :update ],
# :redirect_to => { :action => :list }
def list
@user_pages, @users = paginate :users, :per_page => 10
end
def show
@user = User.find(params[:id])
@show_nav_bar = true
render(:layout => 'submission', :action => 'show')
end
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
flash[:notice] = 'User was successfully created.'
redirect_to :action => 'list'
else
render :action => 'new'
end
end
def edit
@user = User.find(session[:user_id])
end
def update
@user = User.find(params[:id])
params[:user].each do |k, v|
@user.update_attribute(k, v)
end
redirect_to :action => 'show', :id => @user
# if @user.update_attributes(params[:user]) # update_attributes causes validations to execute which is causing
# flash[:notice] = 'User was successfully updated.' # probs when fields that are not updated from the User edit screen
# redirect_to :action => 'show', :id => @user # are validated when we dont want them to be.
# else
# render :action => 'edit'
# end
end
# System Admin only allowed to do this
def destroy
User.find(params[:id]).destroy
redirect_to :action => 'list'
end
# ------------------------------------------------------
# need code to allow only Submission Admin or System Admin to do this
def remove_user_from_submission
SubmissUser.delete_all('user_id = ' + params[:id] + ' and submission_id = ' + session[:submiss_id])
redirect_to(:controller => 'submission', :action => 'list_users')
end
private
def is_member_of
if session[:user_role] == 'admin'
return true
else
redirect_to(:controller => 'submission', :action => 'show_my')
return false
end
end
end
|
# Your Names
# 1) George Wambold
# 2) Regina Compton
# We spent [1.5] hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, order_quantity) #method with two arguments
library = {"cookie" => 1, "cake" => 5, "pie" => 7} #hash
unless library.include?(item_to_make)
raise ArgumentError.new("#{item_to_make} is not a valid input")
end #unless
serving_size = library[item_to_make]
serving_size_mod = order_quantity % serving_size
if serving_size_mod == 0
return "Calculations complete: Make #{order_quantity/serving_size} of #{item_to_make}"
elsif serving_size_mod >= 7
return "Calculations complete: Make #{order_quantity/serving_size} of #{item_to_make}, you have #{serving_size_mod} leftover ingredient(s). You can make #{serving_size_mod/7} more pie(s) plus #{serving_size_mod % 7} more cookies."
elsif serving_size_mod >= 5
return "Calculations complete: Make #{order_quantity/serving_size} of #{item_to_make}, you have #{serving_size_mod} leftover ingredient(s). You can make #{serving_size_mod/5} more cake(s) plus #{serving_size_mod % 5} more cookies."
else
return "Calculations complete: Make #{order_quantity/serving_size} of #{item_to_make}, you have #{serving_size_mod} leftover ingredient(s). You can have #{serving_size_mod/1} more cookie(s)."
end #if
end #def
p serving_size_calc("pie", 7)
p serving_size_calc("pie", 8)
p serving_size_calc("cake", 5)
p serving_size_calc("cake", 7)
p serving_size_calc("cookie", 1)
p serving_size_calc("cookie", 10)
p serving_size_calc("THIS IS AN ERROR", 5)
# Reflection
=begin
-What did you learn about making code readable by working on this challenge?
Concentrating on readability means chosing good method and variable names.
Reading through good code should be sort of like reading a sentance in english,
like IF jacket_size < chest_size then puts "this jacket's too small!". Even
someone who's never written a line of Ruby would probably understand that code.
Did you learn any new methods? What did you learn about them?
No new methods in this challenge, but there was a lot of exposure to modulus,
which is something I'm slowly getting a better grasp on.
What did you learn about accessing data in hashes?
That you can access data in hashes by key just like an array. But I kind of
already knew that. Nothing super new with hashes.
What concepts were solidified when working through this challenge?
Like I said, it was awesome to get more exposure to modulus and seeing how
it's used. Also it was nice to mess with hashes a little bit, up to this point
most challenges have featured arrays.
=end |
SeoApp.configure do |config|
# Postgress config
config.db_url = ENV['DATABASE_URL']
config.adapter = 'sequel'
end
|
require_relative 'boot'
# Typically, rails uses a `require 'rails/all' here, but in our case,
# since we override ActiveRecord with Sequel as our ORM of choice, we
# only require what is needed
require "active_model/railtie"
require "active_job/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "action_cable/engine"
require "sprockets/railtie"
require "rails/test_unit/railtie"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
# Set a global constant to reference current school year
CURRENT_SCHOOL_YEAR = begin
t = Time.now.to_date
((t >= "#{t.year}-07-31".to_date) && t.month <= 12) ? t.year + 1 : t.year
end
module SchoolStatus
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# JasperSoft Configuration {{{
# -----------------------------------------------------------------------------
config.x.jasper.root = ENV['JASPER_URI'] || 'http://skagos.local:8080/jasperserver-pro'
config.x.jasper.user_key = '87fe4f01bd121f1363b1d6e530a67f76'
config.x.jasper.admin = 'ss-admin'
config.x.jasper.password = 'outtatime'
config.x.jasper.admin_ui = '/flow.html?_flowId=homeFlow&theme=ss_admin'
config.x.jasper.adhoc = '/flow.html?_flowId=adhocFlow&mode=browse&theme=default'
config.x.jasper.dashboard = '/dashboard/designer.html?theme=default'
config.x.jasper.viewer = '/flow.html?_flowId=searchFlow&mode=search&filterId=resourceTypeFilter&filterOption=resourceTypeFilter-reports&searchText=&theme=default'
# }}}
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
unless ENV['NO_DB']
config.sequel.after_connect = proc do
Sequel::Model.db.extension :pg_array
Sequel::Model.db.extension :pg_json
Doorkeeper.configure do
orm :sequel
resource_owner_authenticator do
User[session[:'warden.user.default.key']] || redirect_to('/login')
end
access_token_generator '::Doorkeeper::JWT'
authorization_code_expires_in 60.minutes
access_token_expires_in 4.hours
end
Doorkeeper::JWT.configure do
token_payload do |opts|
user = User[opts[:resource_owner_id]]
{
:user => {
:id => user.id,
:username => user.username,
:first_name => user.first_name,
:last_name => user.last_name
}
}
end
secret_key "foobar"
end
end
end
end
end
|
class CreateStudents < ActiveRecord::Migration
def self.up
create_table :students do |t|
t.string :global_file_number
t.integer :person_id
t.integer :occupation_id
t.datetime :busy_starts_at
t.datetime :busy_ends_at
t.string :blood_group
t.string :blood_factor
t.string :emergency
t.integer :health_coverage_id
t.string :older_of_merit
t.string :folio_number
t.timestamps null: false
end
#add_foreign_key :students, :health_coverages
end
def self.down
drop_table :students
end
end
|
class Drink < ApplicationRecord
belongs_to :shop
has_many :takes, foreign_key: 'drink_id', dependent: :destroy
has_many :users, through: :takes, source: :user
end
|
class AddWillUnregisterToAttendees < ActiveRecord::Migration
def self.up
add_column :attendees, :will_unregister, :boolean, :default => false
end
def self.down
remove_column :attendees, :will_unregister
end
end
|
class CreateRsvpInvitesSongs < ActiveRecord::Migration
def self.up
# Create the association table
create_table :rsvp_invites_songs, :id => false do |t|
t.integer :rsvp_invite_id, :null => false
t.integer :song_id, :null => false
end
# Add table index
add_index :rsvp_invites_songs, [:rsvp_invite_id, :song_id], :unique => true
end
def self.down
remove_index :rsvp_invites_songs, [:rsvp_invite_id, :song_id]
drop_table :rsvp_invites_songs
end
end
|
class AddIndexestoEverything < ActiveRecord::Migration[5.1]
def change
add_index :speeds, [:store_id, :shipping_speed], unique: true
add_index :orders, :bc_order_id, unique: true
add_index :amazons, :store_id, unique: true
end
end
|
class Admin::Api::MetricsController < Admin::Api::MetricsBaseController
wrap_parameters Metric, include: [ :name, :system_name, :friendly_name, :unit, :description ]
representer Metric
##~ sapi = source2swagger.namespace("Account Management API")
##~ e = sapi.apis.add
##~ e.path = "/admin/api/services/{service_id}/metrics.xml"
##~ e.responseClass = "List[metric]"
#
##~ op = e.operations.add
##~ op.httpMethod = "GET"
##~ op.summary = "Service Metric List"
##~ op.description = "Returns the list of metrics of a service."
##~ op.group = "metric"
#
##~ op.parameters.add @parameter_access_token
##~ op.parameters.add @parameter_service_id_by_id_name
#
def index
respond_with(metrics)
end
##~ op = e.operations.add
##~ op.httpMethod = "POST"
##~ op.summary = "Service Metric Create"
##~ op.description = "Creates a metric on a service."
##~ op.group = "metric"
#
##~ op.parameters.add @parameter_access_token
##~ op.parameters.add @parameter_service_id_by_id_name
##~ op.parameters.add :name => "friendly_name", :description => "Descriptive Name of the metric.", :dataType => "string", :allowMultiple => false, :required => true, :paramType => "query"
##~ op.parameters.add :name => "system_name", :description => "System Name of the metric. This is the name used to report API requests with the Service Management API. If blank a system_name will be generated for you from the friendly_name parameter", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
##~ op.parameters.add :name => "name", :description => "DEPRECATED: Please use system_name parameter", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
##~ op.parameters.add :name => "unit", :description => "Measure unit of the metric.", :dataType => "string", :allowMultiple => false, :required => true, :paramType => "query"
##~ op.parameters.add :name => "description", :description => "Description of the metric.", :dataType => "text", :allowMultiple => false, :required => false, :paramType => "query"
#
def create
metric = metrics.create(create_params)
respond_with(metric)
end
# swagger
##~ e = sapi.apis.add
##~ e.path = "/admin/api/services/{service_id}/metrics/{id}.xml"
##~ e.responseClass = "metric"
#
##~ op = e.operations.add
##~ op.nickname = "service_metric"
##~ op.httpMethod = "GET"
##~ op.summary = "Service Metric Read"
##~ op.description = "Returns the metric of a service."
##~ op.group = "metric"
#
##~ op.parameters.add @parameter_access_token
##~ op.parameters.add @parameter_service_id_by_id_name
##~ op.parameters.add @parameter_metric_id_by_id
#
def show
respond_with(metric)
end
##~ op = e.operations.add
##~ op.httpMethod = "PUT"
##~ op.summary = "Service Metric Update"
##~ op.description = "Updates the metric of a service."
##~ op.group = "metric"
#
##~ op.parameters.add @parameter_access_token
##~ op.parameters.add @parameter_service_id_by_id_name
##~ op.parameters.add @parameter_metric_id_by_id
##~ op.parameters.add :name => "friendly_name", :description => "Name of the metric.", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
##~ op.parameters.add :name => "unit", :description => "Measure unit of the metric.", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
##~ op.parameters.add :name => "description", :description => "Description of the metric.", :dataType => "text", :allowMultiple => false, :required => false, :paramType => "query"
#
def update
metric.update_attributes(update_params)
respond_with(metric)
end
##~ op = e.operations.add
##~ op.httpMethod = "DELETE"
##~ op.summary = "Service Metric Delete"
##~ op.description = "Deletes the metric of a service. When you delete a metric or a method, it will also remove all the associated limits across application plans."
##~ op.group = "metric"
#
##~ op.parameters.add @parameter_access_token
##~ op.parameters.add @parameter_service_id_by_id_name
##~ op.parameters.add @parameter_metric_id_by_id
#
def destroy
metric.destroy
respond_with(metric)
end
protected
def metric
@metrics ||= metrics.find(params[:id])
end
end
|
require "application_system_test_case"
class TuitsTest < ApplicationSystemTestCase
setup do
@tuit = tuits(:one)
end
test "visiting the index" do
visit tuits_url
assert_selector "h1", text: "Tuits"
end
test "creating a Tuit" do
visit tuits_url
click_on "New Tuit"
fill_in "Tuit", with: @tuit.tuit
click_on "Create Tuit"
assert_text "Tuit was successfully created"
click_on "Back"
end
test "updating a Tuit" do
visit tuits_url
click_on "Edit", match: :first
fill_in "Tuit", with: @tuit.tuit
click_on "Update Tuit"
assert_text "Tuit was successfully updated"
click_on "Back"
end
test "destroying a Tuit" do
visit tuits_url
page.accept_confirm do
click_on "Destroy", match: :first
end
assert_text "Tuit was successfully destroyed"
end
end
|
module Baison
class PackageDetail < Base
# @price 单价
# @payment 实付金额
attr_accessor :sku, :num, :price, :payment
def attributes
{
:sku => nil,
:num => nil,
:price => nil,
:payment => nil
}
end
end
end |
#
# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
#
# 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.
#
Puppet::Type.newtype(:solaris_vlan) do
@doc = "Manage the configuration of Oracle Solaris VLAN links"
ensurable
newparam(:name) do
desc "The name of the VLAN"
isnamevar
end
newparam(:force) do
desc "Optional parameter to force the creation of the VLAN link"
newvalues(:true, :false)
end
newparam(:temporary) do
desc "Optional parameter that specifies that the VLAN is
temporary. Temporary VLAN links last until the next reboot."
newvalues(:true, :false)
end
newproperty(:lower_link) do
desc "Specifies Ethernet link over which VLAN is created"
end
newproperty(:vlanid) do
desc "VLAN link ID"
end
end
|
class CreateArticles < ActiveRecord::Migration
def change
create_table :articles do |t|
t.references :product, index: true
t.string :system_name
t.string :title
t.boolean :visible, default: false
t.text :meta_keywords
t.text :meta_description
t.text :content
t.timestamps null: false
end
add_foreign_key :articles, :products
end
end
|
class Pet < ActiveRecord::Base
belongs_to :user
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :user_pet_follow_ships
has_many :followers, through: :user_pet_follow_ships, source: :user
default_scope { order('created_at ASC') }
validates :avatar,
attachment_content_type: { content_type: /\Aimage\/.*\Z/ },
attachment_size: { less_than: 5.megabytes }
validates :cover,
attachment_content_type: { content_type: /\Aimage\/.*\Z/ },
attachment_size: { less_than: 5.megabytes }
has_attached_file :avatar,
styles: { thumb: '200x200>', square: '200x200#', medium: '500x500>', large: '1000x1000>' },
path: ":rails_root/public/assets/:class/:attachment/:id_:style_:filename",
url: "/assets/:class/:attachment/:id_:style_:filename",
default_url: "/default.jpg"
has_attached_file :cover,
styles: { thumb: '200x200>', medium: '1000x1000>', large: '2000x2000>' },
path: ":rails_root/public/assets/:class/:attachment/:id_:style_:filename",
url: "/assets/:class/:attachment/:id_:style_:filename",
default_url: "/default_cover.jpg"
def avatar_url
{
ori: avatar.url,
thumb: avatar.url(:thumb),
square: avatar.url(:square),
medium: avatar.url(:medium),
large: avatar.url(:large)
}
end
def cover_url
{
ori: cover.url,
medium: cover.url(:medium),
large: cover.url(:large)
}
end
end
|
# frozen_string_literal: true
class TaskCard::Component < ViewComponent::Base
include TaskHelper
with_collection_parameter :task
def initialize(task:)
@task = task
end
def upcase_task_slug
@task.slug.upcase
end
end
|
#!/usr/bin/env ruby
#
# Usage: hr group
#
# Summary: Print a table under a grouped heading
#
# Help: Given a flat table of information, group by the first "column" and print beneath it as a heading
#
require 'optparse'
require 'ostruct'
options = OpenStruct.new
options.field_separator = /,|:|\t/
options.output_field_separator = "\n"
OptionParser.new do |opts|
opts.banner = "Usage: hr vimbundle [options]"
opts.on("-f", "--field-separator [C]", String, "") do |c|
options.output_field_separator = c or abort("choose a character for output_field_separator")
end
opts.on("-o", "--output-field-separator [C]", String, "") do |c|
options.output_field_separator = c or abort("choose a character for output_field_separator")
end
end.parse!
all = []
ARGF.each_line do |line|
all << line.chomp.split(options.field_separator, 2)
end
all.group_by(&:first).each do |heading, grouped|
puts heading
puts grouped.flat_map { |(_, *rest)| rest }.join(options.output_field_separator)
puts
end
|
class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories
has_many :comments
has_many :users, through: :comments
accepts_nested_attributes_for :categories
def categories_attributes=(category_info)
category_info.values.each do |category_name|
if category_name["name"]!=""
category=Category.find_or_create_by(category_name)
self.categories<<category
end
end
end
end
|
require 'test_helper'
class StructureTypesControllerTest < ActionDispatch::IntegrationTest
setup do
@structure_type = structure_types(:one)
end
test "should get index" do
get structure_types_url
assert_response :success
end
test "should get new" do
get new_structure_type_url
assert_response :success
end
test "should create structure_type" do
assert_difference('StructureType.count') do
post structure_types_url, params: { structure_type: { description: @structure_type.description, name: @structure_type.name, status: @structure_type.status, user_id: @structure_type.user_id } }
end
assert_redirected_to structure_type_url(StructureType.last)
end
test "should show structure_type" do
get structure_type_url(@structure_type)
assert_response :success
end
test "should get edit" do
get edit_structure_type_url(@structure_type)
assert_response :success
end
test "should update structure_type" do
patch structure_type_url(@structure_type), params: { structure_type: { description: @structure_type.description, name: @structure_type.name, status: @structure_type.status, user_id: @structure_type.user_id } }
assert_redirected_to structure_type_url(@structure_type)
end
test "should destroy structure_type" do
assert_difference('StructureType.count', -1) do
delete structure_type_url(@structure_type)
end
assert_redirected_to structure_types_url
end
end
|
class Dragon
def initialize name
@name = name
@asleep = false
@stuff_in_belly = 10 #he's full
@stuff_in_intestine = 0 #no poo needed
puts "#{@name} is born."
end
def feed
puts "You feed #{@name}."
@stuff_in_belly = 10
passage_of_time
end
def walk #take him for a dump
puts "You walk #{@name} and they have a good dump."
@stuff_in_intestine = 0
passage_of_time
end
def put_to_bed
puts "You put #{@name} to bed."
@asleep = true
3.times do
if @asleep
passage_of_time
end
if @asleep
puts "#{@name} snores, filling he room with smoke."
end
end
if @asleep
@asleep = false
puts "#{@name} wakes up slowly."
end
end
def toss
puts "You toss #{@name} up into the air."
puts "They giggle which singes your eyebrows."
passage_of_time
end
def rock
puts "You rock #{@name} gently."
@asleep = true
puts "it breifley dozes off...."
passage_of_time
if @asleep
@asleep = false
puts "...but wakes up when you stop."
end
end
private
#methods defined here are internal to the object
def hungry?
@stuff_in_belly <= 2
end
def poopy?
@stuff_in_intestine >= 8
end
def passage_of_time
if @stuff_in_belly > 0
#move from belly to intestine
@stuff_in_belly = @stuff_in_belly - 1
@stuff_in_intestine = @stuff_in_intestine + 1
else #our dragon is starving
if @asleep
@asleep = false
puts "wakes up suddenly!."
end
puts "#{@name} is starving! In desperation they ate YOU!"
exit #quits program
end
if @stuff_in_intestine >= 10
@stuff_in_intestine = 0
puts "Whoops! #{@name} had an accident... hot dragon poo melts your floor!!! "
end
if hungry?
if @asleep
@asleep = false
puts "Wakes up suddenly!"
end
puts "#{@name}'s stomach grumbles"
end
if poopy?
if @asleep
@asleep = false
puts "Wakes up suddenly!"
end
puts "#{@name}'s does the poo poo dance"
end
end
end
puts "what would you like to call your dragon?"
name = gets.chomp
pet = Dragon.new "#{name}"
puts " What would you like to do with your dragon"
while true
puts "What do you want to do?"
puts " feed, walk, put to bed, toss, rock or bye?"
command = gets.chomp
if pet.respond_to?(command)
pet.send(command)
else
puts "your dragon does not know that command"
end
end
|
shared_examples "validated_types" do
context "nil" do
before { instance.string1 = nil }
it "is invalid" do
expect(subject).to eql false
end
end
context "empty String" do
before { instance.string1 = "" }
it "is invalid" do
expect(subject).to eql false
end
end
context "space String" do
before { instance.string1 = " " }
it "is invalid" do
expect(subject).to eql false
end
end
context "random String" do
before { instance.string1 = "random" }
it "is invalid" do
expect(subject).to eql false
end
end
end |
require 'minitest/autorun'
require 'grader-utils'
class TestParseArray < MiniTest::Unit::TestCase
def test_that_it_accepts_array_with_square_brackets
assert_equal GraderUtils.parse_array("[1,2,3]"), ["1", "2", "3"]
assert_equal GraderUtils.parse_array("['1',2,3]"), ["'1'", "2", "3"]
end
def test_that_it_accepts_array_without_square_brackets
assert_equal GraderUtils.parse_array("1,2,3"), ["1", "2", "3"]
assert_equal GraderUtils.parse_array("'1',2,3"), ["'1'", "2", "3"]
end
def test_that_it_ignores_white_spaces
assert_equal GraderUtils.parse_array("1, 2, 3"), ["1", "2", "3"]
assert_equal GraderUtils.parse_array("[ '1', 2, 3\n]"), ["'1'", "2", "3"]
end
end
|
# ==========================================================================
# Project: Lebowski Framework - The SproutCore Test Automation Framework
# License: Licensed under MIT license (see License.txt)
# ==========================================================================
module Lebowski
module RSpec
module Operators
class That < Operator
def initialize(sym, *args)
@sym = sym
@args = args
end
def evaluate(value)
case operator
when :not_empty
return not_empty? value
when :empty
return empty? value
when :between
return between? value
when :at_most
return at_most? value
when :at_least
return at_least? value
when :greater_than
return greater_than? value
when :less_than
return less_than? value
when :contains
return contains? value
when :matches
return matches? value
when :equals
return equals? value
when :equal_to
return equals? value
else
raise ArgumentError "Invalid that operator: #{operator}"
end
end
def operator()
["that_is_", "that_"].each do |prefix|
if @sym =~ /^#{prefix}/
return @sym.to_s.sub(prefix, "").to_sym
end
end
end
def method_missing(sym, *args, &block)
return self
end
private
def not_empty?(value)
return (not empty? value)
end
def empty?(value)
return true if value.nil?
return value.length == 0 if value.kind_of?(Array) or value.kind_of?(String)
return false
end
def between?(value)
return false if not value.kind_of? Numeric
min = @args[0]
max = @args[1]
return ((value >= min) and (value <= max))
end
def at_least?(value)
return false if not value.kind_of? Numeric
return value >= @args[0]
end
def at_most?(value)
return false if not value.kind_of? Numeric
return value <= @args[0]
end
def greater_than?(value)
return false if not value.kind_of? Numeric
return value > @args[0]
end
def less_than?(value)
return false if not value.kind_of? Numeric
return value < @args[0]
end
def contains?(value)
return false if value.nil?
if value.kind_of? String
return false if @args.length > 1
return value == @args[0]
elsif value.kind_of? Array
return @args.all? do |x|
value.member? x
end
end
return false
end
def matches?(value)
return Lebowski::RSpec::Util.match?(@args[0], value)
end
def equals?(value)
return @args[0] == value
end
end
end
end
end |
class Course < ActiveRecord::Base
has_many :students
after_initialize :set_max_participants
def set_max_participants
self.max_participants = 30
end
end
|
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure(2) do |config|
config.vm.box = "ubuntu/trusty64"
config.ssh.insert_key = false
config.ssh.shell = "bash -c 'BASH_ENV=/etc/profile exec bash'"
config.vm.hostname = "online-booking"
config.vm.network :private_network, ip: "192.168.3.100"
config.vm.network "forwarded_port", guest: 3000, host: 3000, auto_correct: true
config.vm.synced_folder ".", "/vagrant", type: "nfs"
config.vm.provider :virtualbox do |vb|
vb.name = "Online booking"
vb.customize ['modifyvm', :id, '--memory', '2048']
end
end |
# questo script serve a creare un file di salvataggio "temporaneo" nel caso
# in cui il gioco si chiuda in modo errato ed il giocatore rischia di perdere
# i progressi di gioco. Purtroppo ci sono alcune chiamate ad API che chiudono
# il gioco mentre si scrive da tastiera e non posso controllarne il comportamento.
# Questo script richiede Homepath Saving.
module Vocab
def self.temp_file_exist
"Sembra l'ultima volta il gioco non si sia chiuso correttamente.\nÈ presente un salvataggio di emergenza. Vuoi caricarlo?"
end
def self.load_temp_save
"Carica e riprendi dall'ultima posizione registrata"
end
def self.delete_temp_save
"No, caricherò un salvataggio (il salvataggio d'emergenza verrà cancellato)"
end
end
module DataManager
TEMP_FILENAME = 'temp_save'
class << self
alias temp_make_filename make_filename
end
def self.create_temp_save
save_game(TEMP_FILENAME)
end
def self.load_temp_save
load_game(TEMP_FILENAME)
end
def self.temp_file_exist?
File.exist?(make_temp_filename)
end
def self.delete_temp_save
return unless temp_file_exist?
delete_save_file(TEMP_FILENAME)
end
# @param [String] index
def self.make_filename(index)
index.is_a?(String) ? make_temp_filename(index) : temp_make_filename(index)
end
# @return [String]
# @param [String] name
def self.make_temp_filename(name = TEMP_FILENAME)
Homesave.saves_path + "/" + name + '.rvdata'
end
end
class Scene_Map < Scene_Base
alias h87_temp_save_start start unless $@
alias h87_temp_save_terminate terminate unless $@
def start
h87_temp_save_start
DataManager.delete_temp_save
end
def terminate
h87_temp_save_terminate
DataManager.create_temp_save
end
end
class Scene_Title < Scene_Base
alias h87_temp_create_command_window create_command_window unless $@
alias h87_temp_open_command_window select_command unless $@
alias h87_temp_update update unless $@
alias h87_temp_terminate terminate unless $@
def create_command_window
create_temp_load_window
h87_temp_create_command_window
end
def create_temp_load_window
@temp_load_window = Window_TempFile.new
@temp_load_window.set_handler(:load_temp, method(:command_load_temp_save))
@temp_load_window.set_handler(:delete_temp, method(:command_delete_temp_save))
end
def command_load_temp_save
fadeout_all
DataManager.load_temp_save
$game_system.on_after_load
SceneManager.goto(Scene_Map)
end
def command_delete_temp_save
@temp_load_window.visible = false
DataManager.delete_temp_save
h87_temp_open_command_window
end
def select_command
if DataManager.temp_file_exist?
@temp_load_window.visible = true
else
h87_temp_open_command_window
end
end
def update
h87_temp_update
@temp_load_window.update if @temp_load_window.visible
end
def terminate
h87_temp_terminate
@temp_load_window.dispose
end
end
class Window_TempFile < Window_Command
def initialize
super(0, 0)
center_window
self.visible = false
end
def window_width
Graphics.width - 60
end
def window_height
fitting_height(4)
end
def make_command_list
add_command(Vocab.load_temp_save, :load_temp)
add_command(Vocab.delete_temp_save, :delete_temp)
end
def item_rect(index)
rect = super
rect.y += (line_height * 2)
rect
end
def refresh
super
draw_text_ex(0, 0, Vocab.temp_file_exist)
end
end |
class HomeController < ApplicationController
def index
@chatrooms = Chatroom.all
end
end
|
class Event < ApplicationRecord
has_many :registrations, dependent: :destroy
validates :name, :location, presence: true
validates :description, length: { minimum: 25 }
validates :price, numericality: { greater_than_or_equal_to: 0 }
validates :capacity, numericality: { only_integer: true, greater_than: 0 }
def self.upcoming
where('start_at > ?', Time.now).order('start_at')
end
def self.past
where('start_at < ?', Time.now).order('start_at')
end
def free?
price.blank? || price.zero?
end
def sold_out?
(capacity - registrations.size).zero?
end
end
|
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :ecm_tournaments_series, :class => 'Ecm::Tournaments::Series' do
sequence(:name) { |i| "Serie ##{i}" }
end
end
|
#! /usr/bin/env ruby
=begin
gtk2/base.rb
Copyright (c) 2006 Ruby-GNOME2 Project Team
This program is licenced under the same licence as Ruby-GNOME2.
$Id: base.rb,v 1.4 2006/11/03 19:40:44 mutoh Exp $
=end
require 'glib2'
require 'atk'
require 'pango'
begin
require 'cairo'
rescue LoadError
end
require 'gtk2.so'
require 'gdk_pixbuf2'
module Gdk
LOG_DOMAIN = "Gdk"
module_function
def cairo_available?
Gdk::Drawable.instance_methods.include?("create_cairo_context")
end
end
module Gtk
LOG_DOMAIN = "Gtk"
class Printer
def self.printers(wait = false)
printers = []
self.each(wait) {|v| printers << v}
printers
end
end
end
GLib::Log.set_log_domain(Gdk::LOG_DOMAIN)
GLib::Log.set_log_domain(Gtk::LOG_DOMAIN)
|
class Configuration
attr_reader :uaa_endpoint
attr_reader :client_name
attr_reader :client_secret
attr_reader :use_ssl
def initialize uaa_endpoint, client_user_name, client_secret, use_ssl
@uaa_endpoint = uaa_endpoint
@client_name = client_user_name
@client_secret = client_secret
@use_ssl = use_ssl
end
end |
class CreateTerritories < ActiveRecord::Migration[5.0]
def change
create_table :territories do |t|
t.string :name
t.string :dsm
t.float :leads_per_hour
t.integer :number_of_stores
t.integer :number_of_hours_worked
t.integer :number_of_active_isps
t.timestamps
end
end
end
|
# frozen_string_literal: true
# Copyright (c) 2018 Robert Haines.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'date'
require 'yaml'
require 'language_list'
require 'spdx-licenses'
require 'cff/version'
require 'cff/util'
require 'cff/model_part'
require 'cff/person'
require 'cff/entity'
require 'cff/reference'
require 'cff/model'
require 'cff/file'
# This library provides a Ruby interface to manipulate CITATION.cff files. The
# primary entry points are Model and File.
#
# See the [CITATION.cff documentation](https://citation-file-format.github.io/)
# for more details.
module CFF
end
|
# frozen_string_literal: true
class Schedule < ApplicationRecord
class Entity < Base
expose :day do |schedule|
schedule.date.day
end
expose :free_seats, if: ->(_, opt) { !(opt[:user]&.admin? || opt[:user]&.operator?) }
expose :date, :count, :free_seats,
if: ->(_, opt) { opt[:user]&.admin? || opt[:user]&.operator? }
end
self.table_name = 'schedule'
has_many :reservations, dependent: :destroy
has_many :users, through: :reservations
validates :date, presence: true, uniqueness: true
validates :count, presence: true
def reserved_seats
reservations.paid.map(&:guests).sum
end
def free_seats
count - reserved_seats
end
end
|
class ReconfigureRepository < ActiveRecord::Migration
def change
rename_column :repositories, :full_name, :provider_id
add_column :repositories, :provider_slug, :string
add_index :repositories, :provider_slug, unique: true
end
end
|
Rails.application.routes.draw do
mount EricWeixin::Engine => "/eric_weixin"
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.