text stringlengths 10 2.61M |
|---|
class DropCatRentalRequestsTable < ActiveRecord::Migration
def up
drop_table :cat_rental_requests
end
def down
raise ActiveRecord::IrreversibleMigration
end
end
|
module ThanksHelper
def some_sample_thanks(count, user=nil)
raise "unsupported" if count > 10
thanks = []
while thanks.count < count
thanks << sample_thank(user)
thanks.uniq!
end
thanks.shuffle
end
def sample_thank(user=nil)
cs = nil
if user && rand(10)==0
cs = context_specific_thank(user)
end
cs || context_free_thank
end
CONTEXT_FREE_THANKS = [
"my loving family",
"my great friends",
"my creativity",
"my good health",
"my good fortune",
"my home",
"my great style",
"funny people",
"the planet",
"my life",
"my childhood",
"a great career",
"good genes",
"my education",
"my love life",
"delicious food",
"technology",
]
def context_free_thank; CONTEXT_FREE_THANKS.sample; end
def context_specific_thank(user)
options = []
options << :parent if user.parent?
options << :partner if user.married? || user.in_a_relationship?
p options
case options.sample
when :parent
"my children"
when :partner
"my loving partner"
end
end
end |
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "taas/version"
Gem::Specification.new do |s|
s.name = "taas"
s.version = Taas::VERSION
s.authors = ["Akash"]
s.email = ["akashm@thoughtworks.com"]
s.homepage = ""
s.summary = %q{Testing As A Services}
s.description = %q{Gem provide a web services interface to run Test as a Services between two independent but related system}
s.rubyforge_project = "taas"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"]
# specify any dependencies here; for example:
# s.add_development_dependency "rspec"
# s.add_runtime_dependency "rest-client"
s.add_dependency "sinatra"
s.add_dependency "test-unit"
end
|
module Fptools
module Pdf
class GutterGenerator
include_package 'com.itextpdf.text'
include_package 'com.itextpdf.text.pdf'
def self.generate(in_file, out_file)
gutter_width = 9
orig = PdfReader.new(in_file)
orig_dims = orig.getPageSizeWithRotation(1)
page_width = orig_dims.getWidth
page_height = orig_dims.getHeight
doc_dims = Rectangle.new(page_width, page_height)
output = Document.new(doc_dims, 0, 0, 0, 0)
writer = PdfWriter.getInstance(output,
java.io.FileOutputStream.new(out_file))
writer.setPDFXConformance(1)
output.open
orig_pages = orig.getNumberOfPages
1.upto(orig_pages) do |page_num|
gutter_position = (page_num % 2 == 0) ? :left : :right
x, y, x1, y1 = (gutter_position == :left) ?
[(page_width - gutter_width), 0, page_width, page_height] :
[0, 0, gutter_width, page_height]
unless page_num == 1
output.setPageSize(orig.getPageSizeWithRotation(page_num))
output.newPage
end
cb = writer.getDirectContent
page = writer.getImportedPage(orig, page_num)
cb.addTemplate(page,0,0)
cb.setCMYKColorStroke(0,0,0,0)
cb.setCMYKColorFill(0,0,0,0)
cb.rectangle(x,y,x1,y1)
cb.fillStroke
end
output.close
out_file
end
end
end
end
|
# Your Names
# 1) Jack Abernathy
# 2) KB DiAngelo
# Guide : Charlotte
# We spent [1] hours on this challenge.
# Bakery Serving Size portion calculator.
def serving_size_calc(item_to_make, order_quantity)
menu = {"cookie" => 1, "cake" => 5, "pie" => 7}
# Error checking
if !menu.has_key?(item_to_make)
raise ArgumentError.new ("#{item_to_make} is not a recognized bakery item.")
end
# Finding serving size and amount of hungry leftover
serving_size = menu[item_to_make]
hungry_people = order_quantity % serving_size
# Returns String based on whether there are hungry people left or not
if hungry_people == 0
puts "Make #{order_quantity/serving_size} of #{item_to_make}"
else
puts "Make #{order_quantity/serving_size} of #{item_to_make}, you have #{hungry_people} hungry people. You should buy #{hungry_people} cookie(s) for them. Or make #{order_quantity/serving_size + 1} of #{item_to_make}. You will have #{serving_size - hungry_people} leftover slices."
end
end
serving_size_calc("pie", 7)
serving_size_calc("pie", 8)
serving_size_calc("cake", 5)
serving_size_calc("cake", 7)
serving_size_calc("cookie", 1)
serving_size_calc("cookie", 10)
# serving_size_calc("salad", 45)
# Reflection
=begin
* What did you learn about making code readable by working on this challenge?
The idea that the very shortest way to write something is not always
the most readable way to write something was solidified in this challenge.
We thought about using return (something) if (something) but our guide
helped us realize that while that was shorter, it was less readable.
* Did you learn any new methods? What did you learn about them?
The only new method we used in this challenge was hash#has_key? which
returns true if the key is present and false if it is not. This method
is great for checking whether a certain hash key is present.
* What did you learn about accessing data in hashes?
There was some really convoluted way to access the value of the key
before we refactored. It is much easier to just write hash[key] to get
a value stored with a hash key.
* What concepts were solidified when working through this challenge?
* The concept of Don't Repeat Yourself
* Correct use of case statments for when there are way more than
2 possible cases (as there were not here).
* Return vs. printing to the console
* Shorter is not always better when it's not readable
=end
|
class CommentsController < ApplicationController
def create
comment = Comment.new(comment_params)
if comment.valid?
if !params[:new_username].empty? && params[:comment][:user_id].empty?
newuser = User.find_or_create_by(username: params[:new_username])
comment.user_id = newuser.id
comment.save
elsif params[:new_username].empty? && !params[:comment][:user_id].empty?
user = User.find(params[:comment][:user_id])
comment.user_id = user.id
comment.save
end
redirect_to comment.post
else
redirect_to comment.post
end
end
private
def comment_params
params.require(:comment).permit(:content, :post_id, :user_id, :new_username, user_attributes:[:username])
end
# def post_params
# params.require(:post).permit(:title, :content, category_ids:[], categories_attributes: [:name])
# end
end
|
module RedisClient
# we should use a connection pool for production apps
# this way we may exhaust redis resource unnecessarily
def self.new_client
Redis.new(host: 'localhost', port: 6379, db: 1)
end
end
|
class Dvd < ActiveRecord::Base
attr_accessible :ASIN, :director, :title, :release_date, :summary
validates :title,
:presence => { :message => "Dvd title is required"}
validates :title,
:uniqueness => { :message => "Dvd title must be unique"}
validates :summary,
:presence => { :message => "Dvd summary is required"}
validates :ASIN,
:format => {:with => /^\w+$/i, :message => "ASIN must be alphanumeric"},
:allow_nil => true,
:allow_blank => true
validates :ASIN,
:length => { :is => 10, :message => "ASIN must be length of 10"},
:allow_nil => true,
:allow_blank => true
end
|
require 'rack/server'
require 'rack/builder'
module Circuit
module Rack
# Extensions to Rack::Builder
module BuilderExt
# @return [Boolean] true if a default app is set
def app?
!!@run
end
# Duplicates the `@use` Array and `@map` Hash instance variables
def initialize_copy(other)
@use = other.instance_variable_get(:@use).dup
unless other.instance_variable_get(:@map).nil?
@map = other.instance_variable_get(:@map).dup
end
end
end
# A Rack::Builder variation that does not require a fully-compliant rackup
# file; specifically that a default app (`run` directive) is not required.
class Builder < ::Rack::Builder
include BuilderExt
# Parses the rackup (or circuit-rackup .cru) file.
# @return [Circuit::Rack::Builder, options] the builder and any parsed options
def self.parse_file(config, opts = ::Rack::Server::Options.new)
# allow for objects that are String-like but don't respond to =~
# (e.g. Pathname)
config = config.to_s
if config.to_s =~ /\.cru$/
options = {}
cfgfile = ::File.read(config)
cfgfile.sub!(/^__END__\n.*\Z/m, '')
builder = eval "%s.new {\n%s\n}"%[self, cfgfile], TOPLEVEL_BINDING, config
return builder, options
else
# this should be a fully-compliant rackup file (or a constant name),
# so use the real Rack::Builder, but return a Builder object instead
# of the app
app, options = ::Rack::Builder.parse_file(config, opts)
return self.new(app), options
end
end
end
end
end
|
class ApplicationController < ActionController::Base
protect_from_forgery unless: -> { request.format.json? }, prepend: true
private
def after_sign_in_path_for(resource)
session["player_return_to"] || root_path
end
end
|
class Player
attr_reader :life
attr_reader :weapon
attr_accessor :spell_damage
attr_reader :field
attr_reader :deck
attr_reader :hand
def initialize
@life = 30
@weapon = nil
@spell = nil
@spell_damage = 0
@field = Field.new
@deck = Deck.new
@hand = Hand.new
end
end
|
class PurchasesController < ApplicationController
before_action :authenticate_user!, only: [:index, :edit]
before_action :getcard_id, only: [:index, :create]
before_action :item_param, only: [:index, :create]
before_action :back_index, only: [:index]
before_action :solditem_to_top, only: [:index]
def index
@purchase_address = PurchaseAddress.new
end
def create
@purchase_address = PurchaseAddress.new(purchases_params)
if @purchase_address.valid?
pay_item
@purchase_address.save
redirect_to root_path
else
render 'index'
end
end
private
def item_param
@item = Item.find(params[:item_id])
end
def solditem_to_top
redirect_to root_path if nil != (Purchase.find_by(item_id: @item.id)) # 商品が購入済みならトップページへ遷移する
end
def purchases_params
params.permit(:item_id, :postal_code, :prefecture_id, :municipality, :address, :building_name, :phone_number).merge(
user_id: current_user.id, price: @item.price
)
end
def getcard_id
Payjp.api_key = ENV["PAYJP_SECRET_KEY"]
card = Card.find_by(user_id: current_user.id)
redirect_to new_card_path and return unless card.present?
customer = Payjp::Customer.retrieve(card.customer_token)
@card = customer.cards.first
end
def pay_item
Payjp.api_key = ENV['PAYJP_SECRET_KEY']
customer_token = current_user.card.customer_token # ログインしているユーザーの顧客トークンを定義
Payjp::Charge.create(
amount: purchases_params[:price],
card: purchases_params[:token],
customer: customer_token, # 顧客のトークン
currency: 'jpy'
)
end
def back_index
redirect_to root_path if current_user.id == @item.user_id
end
end
|
module Sidekick
class LocationSharesController < InheritedResources::Base
InheritedResources.flash_keys = [:success, :failure]
before_filter :authenticate_user!
actions :all, :only => [:new, :create]
defaults :resource_class => Share, :collection_name => 'shares', :instance_name => 'share'
respond_to :html, :js
def create
super {|format| format.html {redirect_to root_url}}
end
private
def begin_of_association_chain
@location = Location.find(params[:location_id])
end
end
end |
class AddAvatarReceiptToItemComments < ActiveRecord::Migration
def change
add_column :item_comments, :avatar_receipt, :string
end
end
|
require './lib/Grid'
class Cell
attr_reader :x, :y, :life, :living_neighbors
def initialize(x, y)
@x = x
@y = y
@life = false
end
def kill
@life = false
end
def give_life
@life = true
end
def anybody_out_there
@living_neighbors = []
Grid.spaces.each do |cell|
if (cell.x == self.x-1 || cell.x == self.x+1 || cell.x == self.x && cell != self) && cell.life == true
living_neighbors << cell
elsif (cell.y == self.y-1 || cell.y == self.y+1 || cell.y == self.y && cell != self) && cell.life == true
living_neighbors << cell
end
end
@living_neighbors
end
def birth
if @living_neighbors.length == 2 || @living_neighbors.length == 3
give_life
elsif @living_neighbors.length < 2 || @living_neighbors.length > 3
kill
else
puts "Shit is over, B!"
end
end
end
|
class Hash
def to_hash_map
hm = java.util.HashMap.new
if block_given?
each do |key, value|
hm.put(*yield(key, value))
end
else
each do |key, value|
hm.put key, value
end
end
hm
end
end
|
require "spec_helper"
describe "govuk collector" do
ARTEFACT_URL = "http://www.gov.uk/api/artefacts.json"
it "should retrieve artefacts from govuk api" do
artefacts = {
results: []
}
FakeWeb.register_uri(:get, ARTEFACT_URL, body: artefacts.to_json)
collector = GovUkCollector.new(ARTEFACT_URL, [])
messages = collector.messages
messages.should be_empty
end
it "should parse the retrieved artefact into a list of messages" do
MessageBuilder.any_instance.stub(:build).with({ "format" => "artefact" }).and_return(:message)
artefacts = {
results: [
{ "format" => "artefact" },
{ "format" => "artefact" },
{ "format" => "artefact" }
]
}
FakeWeb.register_uri(:get, ARTEFACT_URL, body: artefacts.to_json)
collector = GovUkCollector.new(ARTEFACT_URL, ["artefact"])
messages = collector.messages
messages.should have(3).messages
messages[0] == :message
messages[1] == :message
messages[2] == :message
end
it "should return messages only for relevant artefacts" do
MessageBuilder.any_instance.stub(:build).and_return(:message)
MessageBuilder.any_instance.should_not_receive(:build).with({ "format" => "something_else" })
artefacts = {
results: [
{ "format" => "guide" },
{ "format" => "answer" },
{ "format" => "something_else" }
]
}
FakeWeb.register_uri(:get, ARTEFACT_URL, body: artefacts.to_json)
collector = GovUkCollector.new(ARTEFACT_URL, ["guide", "answer"])
messages = collector.messages
messages.should have(2).messages
end
end |
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
helper_method :mailbox, :conversation
helper_method :current_user, :authenticate_user
def require_admin
redirect_to '/prep_courses' unless current_user.admin?
end
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def require_user
redirect_to '/login' unless current_user
end
def authenticate_user
if !current_user
redirect_to signin_path, notice: "You must be signed in to do that!"
end
end
private
def mailbox
@mailbox ||= current_user.mailbox
end
def conversation
@conversation ||= mailbox.conversations.find(params[:id])
end
end
|
module DamperRepairReport
class PhotoSection
include Report::SectionWritable
def write(pdf)
records.each { |r| PhotoPage.new(r).write(pdf) }
end
end
end |
class UsersController < ApplicationController
load_and_authorize_resource
def new
@user=User.new
end
def show
if params[:id].blank?
@user = current_user
else
@user = User.find(params[:id])
end
end
def index
@users = User.paginate(:page => params[:page], :per_page => 10)
end
def create
@user = User.new(user_params)
if @user.save
flash[:notice]="Success user created"
redirect_to user_path(@user)
else
render "new"
end
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:notice] = "Profile updated"
redirect_to user_path(@user)
else
render 'edit'
end
end
def edit
@user=User.find(params[:id])
end
def destroy
@user = User.find(params[:id])
@user.destroy
flash[:success] = "User deleted."
redirect_to users_url
end
private
def user_params
params.require(:user).permit(:email,:user_id, :password,:password_confirmation,
:address,:city,:state,:country,
:bday,:full_name,:login,:zip,:latitude,:longitude,{:role_ids => []})
end
end
|
class RemoveUnnecesaryFields < ActiveRecord::Migration[5.0]
def change
remove_column :categories, :topic_type
remove_column :categories, :topic_id
remove_column :topics, :post_type
remove_column :topics, :post_id
remove_column :users, :post_id
remove_column :users, :thread_id
end
end
|
module Telegram
module Bot
class UpdatesController
# Allows to store context in session and treat next message according to this context.
#
# It provides `save_context` method to store method name
# to be used as action for next update:
#
# def set_location!(*)
# save_context(:set_location_from_message)
# respond_with :message, text: 'Where are you?'
# end
#
# def set_location_from_message(city = nil, *)
# # update
# end
#
# # OR
# # This will support both `/set_location city_name`, and `/set_location`
# # with subsequent refinement.
# def set_location!(city = nil, *)
# if city
# # update
# else
# save_context(:set_location!)
# respond_with :message, text: 'Where are you?'
# end
# end
module MessageContext
extend ActiveSupport::Concern
include Session
# Action to clear context.
def cancel!
# Context is already cleared in action_for_message
end
private
# Controller may have multiple sessions, let it be possible
# to select session for message context.
def message_context_session
session
end
# Fetches context and finds handler for it. If message has new command,
# it has higher priority than contextual action.
def action_for_message
val = message_context_session.delete(:context)
context = val && val.to_s
super || context && begin
args = payload['text'].try!(:split) || []
action = action_for_message_context(context)
[[action, type: :message_context, context: context], args]
end
end
# Save context for the next request.
def save_context(context)
message_context_session[:context] = context
end
# Returns action name for message context. By default it's the same as context name.
# Raises AbstractController::ActionNotFound if action is not available.
# This differs from other cases where invalid actions are silently ignored,
# because message context is controlled by developer, and users are not able
# to construct update to run any specific context.
def action_for_message_context(context)
action = context.to_s
return action if action_method?(action)
raise AbstractController::ActionNotFound,
"The context action '#{action}' is not found in #{self.class.name}"
end
end
end
end
end
|
require "formula"
class PcscLite < Formula
homepage "http://pcsclite.alioth.debian.org"
url "https://alioth.debian.org/frs/download.php/file/4126/pcsc-lite-1.8.13.tar.bz2"
sha1 "baa1ac3a477c336805cdf375912da5cbc8ebab8d"
bottle do
sha1 "8b726aaf4467583d1fd808650229757c9561c4d5" => :yosemite
sha1 "42eff3939a65ea2cea53b8a61dc60321c01cb00f" => :mavericks
sha1 "3600bfdc0d7e74f27c0c0474660805f58378e903" => :mountain_lion
end
def install
system "./configure", "--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
end
test do
system sbin/"pcscd", "--version"
end
end
|
class Train
def initialize(number, type, waggons)
$number = number
@type = type
@waggons = waggons
@speed = 0
end
def speed_up
@speed += 10
@speed = 110 if @speed > 110
end
def print_sp
puts "Current speed of #{@number} is #{@speed} kmh"
end
def speed_down
@speed -= 10
@speed = 0 if @speed < 0
end
def add_wag
if @speed == 0
@waggons += 1
else puts "Stop the train to add waggons"
end
end
def rem_wag
if @speed == 0
if @waggons > 0
@waggons -= 1
else puts "There is no waggons to remove"
end
else puts "Stop the train to remove waggons"
end
end
def print_wag
puts "Number of waggons is #{@waggons}"
end
end
class Station
def initialize(name)
@name = name
@arrived_trains = []
end
def arrive(number)
@arrived_trains << number
end
def print_trains
print @arrived_trains
end
def print_trains_by_type(type)
station_trains_by_type = []
@arrived_trains.each do |train|
print train
end
print station_trains_by_type
end
def depat(number)
@arrived_trains.delete(number)
end
end
|
class AssistiveTechnology < ActiveRecord::Base
belongs_to :platform, inverse_of: :assistive_technologies
has_many :matrixEntries, inverse_of: :assistive_technology
end
|
class CategoriesController < ApplicationController
before_filter :authenticate_user!
def index
@categories = Category.all
end
def new
@category = Category.new()
end
def edit
@category = Category.find(params[:id])
end
def update
@category = Category.find(params[:id])
if @category.update_attributes(category_params)
redirect_to categories_path
else
render :action => "edit"
end
end
def create
@category = Category.create(category_params)
if @category.valid?
flash[:success] = "Your category was saved!"
redirect_to categories_path
else
flash[:error] = "Your category could not be saved. please try again."
render "new"
end
end
def category_params
params.require(:category).permit(:image, :name)
end
end
|
require "json"
require "open-uri"
class TodoSorter
def initialize(formats)
@formats = formats
end
def sort(results)
results.sort_by do |c|
[
-c.num_exh_votes,
-$CardDatabase.decks_containing(c).count
] + @formats.map{|format| (format.legality(c).nil? ? 3 : format.legality(c).start_with?("banned") ? 2 : (format.legality(c).start_with?("restricted") ? 1 : 0))} + [
c.commander? ? 0 : (c.brawler? ? 1 : 2),
c.release_date_i,
c.color_identity.size,
c.default_sort_index
]
end
end
def warnings
[]
end
end
class XmageController < ApplicationController
def index
redirect_to(controller: "downloads", action: "index", anchor: "xmage")
end
def xmage_config # can't be named config because of https://github.com/rails/rails/issues/29217
today_config = JSON.load(open("http://xmage.today/config.json"))
base_url = dev? ? "https://dev.lore-seeker.cards" : "https://lore-seeker.cards"
version_file = (Pathname(__dir__) + "../../../data/xmage-version.txt")
version = version_file.exist? ? version_file.read.strip : "unknown"
render json: {
java: today_config["java"],
XMage: {
version: version,
location: "#{base_url}/download/xmage-update.zip",
locations: [],
full: "#{base_url}/download/xmage.zip",
torrent: "",
images: "",
Launcher: today_config["XMage"]["Launcher"]
}
}
end
def news
@title = "new XMage cards"
@entries = []
date = dev? ? Date.new(2019, 9, 24) : Date.new(2020, 3, 3)
cards = Set[]
until date > Date.today do
if date > Date.new(2019, 9, 24) and $XmageCache.get(date).nil?
date += 1
next
end
query = Query.new("st:custom is:mainfront game:xmage", dev: dev?)
query.cond.metadata! :time, date
results = $CardDatabase.search(query).card_groups.map do |printings|
with_best_printing(printings).first
end
next_cards = results.map(&:card).to_set
if next_cards != cards
@entries.insert(0, [date, results.reject{|best_printing| cards.include?(best_printing.card)}.sort])
cards = next_cards
end
date += 1
end
end
def todo
@title = "XMage card todo list"
@formats = [
Format["custom standard"].new,
Format["custom brawl"].new,
Format["elder custom highlander"].new,
Format["custom eternal"].new
]
page = [1, params[:page].to_i].max
#TODO special section for unknown implemented cards in Lore Seeker custom sets, if any (possible typos)
#TODO special section for reprints of implemented cards, if any
search = "st:custom is:mainfront -game:xmage"
query = Query.new(search, dev: dev?)
query.sorter = TodoSorter.new(@formats)
results = $CardDatabase.search(query)
@cards = results.card_groups.map do |printings|
with_best_printing_and_rotation_info(printings)
end
@cards = @cards.paginate(page: page, per_page: 100)
end
def vote
return redirect_to("/auth/discord") unless signed_in?
card = exh_card(params[:name])
if card.voters.include?(current_user)
card.remove_vote!(current_user)
else
card.add_vote!(current_user)
end
redirect_back fallback_location: {controller: "card", action: "index", params: {q: card.name}}
end
def exh_index
redirect_to(controller: "format", action: "show", id: "elder-xmage-highlander")
end
def exh_news
redirect_to(action: "news")
end
def exh_todo
redirect_to(action: "todo")
end
private
def with_best_printing(printings)
best_printing = printings.find{|cp| ApplicationHelper.card_picture_path(cp) } || printings[0]
[best_printing, printings]
end
def with_best_printing_and_rotation_info(printings)
best_printing, printings = with_best_printing(printings)
exh_card = ExhCard.find_by(name: best_printing.name)
[best_printing, printings, exh_card && exh_card.rotation]
end
end
|
def bubble_sort(sort_array)
# set swapcounter to non zero value
swap_count = 1
## loop swap counter != 0
while swap_count != 0
# set swap counter to 0
swap_count = 0
# loop through each element in array
sort_array.each_with_index do |item, index|
if sort_array[index + 1]
# check adjacent elements are in order swap if not
if item > sort_array[index + 1]
sort_array[index] = sort_array[index + 1]
sort_array[index + 1] = item
swap_count += 1
end
end
end
end
sort_array
end
p bubble_sort([4, 3, 78, 20, 0, 2])
|
# UpdatesWorker.perform_async
class UpdatesWorker
include Sidekiq::Worker
sidekiq_options queue: 'updates', retry: true
def perform
Settings.strategies.each do |strategy|
"#{strategy.capitalize}Strategy".constantize.new.check_for_updates
end
end
end |
LiminalApparel::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
config.log_level = :info # :warn # required to stop Ruby crashing under Windows when more verbose log levels are used
# - see https://rails.lighthouseapp.com/projects/8994/tickets/5590 and
# http://redmine.ruby-lang.org/issues/show/3840
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true
config.action_mailer.smtp_settings = { :address => "smtp.clear.net.nz" }
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
Site.domains = {
:new_zealand => "dev.liminal.org.nz",
:australia => "dev.liminal.org.au"
}
# In development, all domains should resolve to localhost
require "resolv"
Site.domains.values.each do |domain|
address = Resolv.getaddress(domain) rescue nil
unless address == "127.0.0.1"
puts "[WARNING] #{domain} does not resolve to 127.0.0.1. Please add it to /etc/hosts"
end
end
end
|
class Intervention < ActiveRecord::Base
belongs_to :parliament_member
belongs_to :session
has_many :intervention_words
def to_hash
{ :parliament_member_id => parliament_member_id,
:date => date,
:content => content,
:sequence => sequence || -1,
:session_id => session.id,
:session_identifier => session.identifier,
:parliament_member => parliament_member.to_hash,
:words_json => intervention_words.select{|w| w.relevant }.map(&:to_hash) }
end
def to_json
to_hash.to_json
end
end
|
module Endpoints
class Users < Sapp::Base
index 'users' do
'All users'
end
show 'user' do
'One User'
end
end
end
|
# A join class of sorts between nouns and user. Tracks references
# to which user created specific nouns.
class NounCreator < ActiveRecord::Base
belongs_to :noun, polymorphic: true
belongs_to :user
validates_presence_of :user
validates_presence_of :noun
end
|
require "rails_helper"
RSpec.describe MyFacilitiesHelper, type: :helper do
describe "patient_days_css_class" do
it "is nil if patient_days is nil" do
expect(patient_days_css_class(nil)).to be_nil
end
it "returns red-new if < 30" do
expect(patient_days_css_class(29)).to eq("bg-red")
end
it "is orange for 30 to < 60" do
expect(patient_days_css_class(35)).to eq("bg-orange")
end
it "is yellow-dark for 60 to < 90" do
expect(patient_days_css_class(66)).to eq("bg-yellow")
end
it "is green for more than 90" do
expect(patient_days_css_class(91)).to eq("bg-green")
end
it "can change the prefix for the css class" do
expect(patient_days_css_class(29, prefix: "c")).to eq("c-red")
expect(patient_days_css_class(200, prefix: "c")).to eq("c-green")
end
end
describe "#opd_load" do
let!(:facility) { create(:facility, monthly_estimated_opd_load: 100) }
it "returns nil if the selected period is not :month or :quarter" do
expect(opd_load(facility, :day)).to be_nil
end
it "returns the monthly_estimated_opd_load if the selected_period is :month" do
expect(opd_load(facility, :month)).to eq 100
end
it "returns the 3 * monthly_estimated_opd_load if the selected_period is :quarter" do
expect(opd_load(facility, :quarter)).to eq 300
end
end
end
|
class LawsuitsController < ApplicationController
before_action :authenticate_user!
before_action :set_lawsuit, only: [:show, :edit, :update, :destroy]
# GET /lawsuits
def index
@lawsuits = Lawsuit.all
end
# GET /lawsuits/1
def show
end
# GET /lawsuits/new
def new
@lawsuit = Lawsuit.new
end
# POST /lawsuits
def create
params = lawsuit_params
if params[:web_resource_id] == ''
params[:web_resource_id] = nil
end
@lawsuit = Lawsuit.new(lawsuit_params)
respond_to do |format|
if @lawsuit.save
format.html { redirect_to @lawsuit, notice: t(:operation_successful) }
else
format.html { render :new }
end
end
end
# GET /lawsuits/1/edit
def edit
end
# PATCH/PUT /lawsuits/1
def update
respond_to do |format|
if @lawsuit.update(lawsuit_params)
format.html { redirect_to @lawsuit, notice: t(:operation_successful) }
else
format.html { render :edit }
end
end
end
# DELETE /lawsuits/1
def destroy
@lawsuit.destroy
respond_to do |format|
format.html { redirect_to lawsuits_url, notice: t(:operation_successful) }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_lawsuit
@lawsuit = Lawsuit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def lawsuit_params
params.require(:lawsuit).permit(:name, :weight, :subcategory_id, :web_resource_id)
end
end
|
# -*- coding: utf-8 -*-
class SoliderQueuesController < ApplicationController
before_filter :authenticate_user
before_filter :find_city
def new
end
# 增加一批新的训练士兵的任务
def create
if @city.waiting_solider_queues.count >= 5
flash[:notice] = '等待接受训练的批次已经达到5批'
redirect_to :action => 'new'
return
end
solider = params[:solider]
case solider[:kind].to_i
when Solider::Codes['长枪兵']
Solider.study_cqb(@city.id, solider[:num].to_i)
when Solider::Codes['弓箭手']
Solider.study_gjs(@city.id, solider[:num].to_i)
when Solider::Codes['骑兵']
Solider.study_qb(@city.id, solider[:num].to_i)
end
redirect_to :action => 'new'
end
# 取消士兵训练队伍,并且退换金子
def destroy
sq = SoliderQueue.find(params[:id])
sq.remove_delayed
sq.return_gold
sq.destroy
redirect_to :action => 'new'
end
private
def find_city
@city = current_user.cities.find(params[:city_id])
end
end
|
class DepartmentDocumentsController < ApplicationController
before_filter :find_doc
before_filter :authenticate_user!
def edit
respond_to do |format|
format.html { render layout: !request.xhr? }
end
end
# PUT text_documents/1
# PUT text_documents/1.json
def update
if @doc.update_from_params(params[:department_document])
render json: @doc, status: :ok
else
render json: doc.errors, status: :unprocessable_entity
end
end
private
def find_doc
dept = Department.find params[:dept_id]
@doc = dept.homepage_docs.find params[:id]
end
end
|
require 'rails_helper'
RSpec.describe 'Category', type: :system do
describe 'Category function' do
let(:user) { create(:user) }
let!(:category) { create(:category) }
let!(:category1) { create(:category, :category1) }
let!(:post) { create(:post, category_ids: [category.id]) }
let!(:post1) { create(:post, category_ids: [category.id]) }
let!(:post2) { create(:post, category_ids: [category.id]) }
let!(:post3) { create(:post, category_ids: [category.id]) }
let!(:post4) { create(:post, category_ids: [category.id]) }
let!(:post5) { create(:post, category_ids: [category.id]) }
before do
sign_in(user.email, user.password)
visit root_path
end
it 'サイドバーにカテゴリの一覧が表示されている' do
expect(page).to have_css '.ca-name', count: 2
end
it 'カテゴリーリンクを踏むと、そのカテゴリーに属する投稿がでる' do
click_on category.name
expect(page).to have_content "カテゴリー(#{category.name})"
end
it '投稿詳細では、投稿が属するカテゴリー名が表示されている' do
visit post_path(post.id)
post.categories.each do |category|
expect(page).to have_content category.name
end
end
it '投稿詳細で表示されているカテゴリー名を押すと、カテゴリーページに移動する' do
visit post_path(post.id)
post.categories.each do |category|
click_on category.name
expect(current_path).to eq category_path(category.id)
end
end
it '投稿された漫画に関連する漫画が4つまで表示され,自分は含まれない' do
visit post_path(post.id)
within '.category-posts' do
expect(page).to have_css '.category-post', count: 4
expect(page).not_to have_selector '.category_post', text: post.title
end
end
end
end
|
# Version module
module ToyRobot
# Toy Robot Simulator version
VERSION = "1.0.0"
end
|
class WechatKey < ActiveRecord::Base
belongs_to :instance
validates :tips, :key, :msg_type, :content, presence: true
validates_uniqueness_of :key, scope: :instance_id
mount_uploader :banner, BannerUploader
TYPES = {
text: '纯文本',
news: '图文消息'
}
end
|
class AddPublishedAtToArticles < ActiveRecord::Migration
def self.up
add_column :articles, :published_at, :datetime
Article.all.each do |article|
if article.published
article.update_attributes!(:published_at => article.created_at)
end
end
end
def self.down
remove_column :articles, :published_at
end
end
|
module ApplicationHelper
def resource_name
:user
end
def resource
@resource ||= User.new
end
def devise_mapping
@devise_mapping ||= Devise.mappings[:user]
end
#/////////////////////devise//////////////////////////
# def render_country_category(country)
# key = CountryData.country_categories.key(country.country_category)
# I18n.t("country_categories.#{key}")
# end
def notice_message
alert_types = { notice: :success, alert: :danger }
close_button_options = { class: "close", "data-dismiss" => "alert", "aria-hidden" => true }
close_button = content_tag(:button, "×", close_button_options)
alerts = flash.map do |type, message|
alert_content = close_button + message
alert_type = alert_types[type.to_sym] || type
alert_class = "alert alert-#{alert_type} alert-dismissable text-center"
alert_id = "alert-messages"
content_tag(:div, alert_content, class: alert_class)
end
alerts.join("\n").html_safe
end
protected
# def check_user_login!
# if !user_signed_in
# flash[:devise_alert] = "確實填寫欄位"
# render :_new
# # redirect_to login_path, :notice => 'if you want to add a notice'
# ## if you want render 404 page
# ## render :file => File.join(Rails.root, 'public/404'), :formats => [:html], :status => 404, :layout => false
# end
# end
end
|
# frozen_string_literal: true
module VmTranslator
module Commands
Call = Struct.new(:function_name, :arguments_number) do
def accept(visitor)
visitor.visit_call(self)
end
end
end
end
|
dep "code" do
met? { shell("file -b ~/code") == "directory" }
meet { shell("mkdir -p ~/code") }
end |
class Api::V1::BaseResource < JSONAPI::Resource
class << self
def verify_key(key, context = nil)
if key.is_a?(Hash)
if key.key?(:attributes)
key
else
if key.key?(:id)
key = key[:id]
super
else
fail 'Actually we can not handle hashes without attributes.'
end
end
else
super
end
end
end
def _replace_fields(field_data)
ActiveRecord::Base.transaction do
# initialize model
super(field_data.reject { |key, _value| key.in?(%i(to_one to_many)) })
# binding.pry
# associations are build later so we can not check for parent orga here:
_model.skip_unset_inheritance = true
if context[:current_user]
_model.area = context[:current_user].area
end
_model.save # TODO: save!
# handle associations
field_data[:to_one].each do |relationship_type, value|
if value.nil?
remove_to_one_link(relationship_type)
else
case value
when Hash
if value.fetch(:id) && value.fetch(:type)
replace_polymorphic_to_one_link(relationship_type.to_s, value.fetch(:id), value.fetch(:type))
# TODO: Do we need that? Is it possible to create polymorphic objects? → Maybe locatable, contactable?
# elsif value.fetch(:type)
# # create polymorphic
# handle_associated_object_creation(:to_one, relationship_type, value)
else
# create
handle_associated_object_creation(:to_one, relationship_type, value)
end
when Integer, String
value = { id: value }
end
# TODO: Does this work correctly?
relationship_key_value = value[:id]
replace_to_one_link(relationship_type, relationship_key_value)
end
end if field_data[:to_one]
field_data[:to_many].each do |relationship_type, values|
# _model.send("#{relationship_type}=", [])
values.map! do |data|
handle_associated_object_creation(:to_many, relationship_type, data)
end
relationship_key_values = values.map { |v| v[:id] }
replace_to_many_links(relationship_type, relationship_key_values)
end if field_data[:to_many]
end
end
def _replace_to_many_links(relationship_type, relationship_key_values, options)
super
end
private
def handle_associated_object_creation(association_type, relationship_type, values)
if values.is_a?(Integer)
values = { id: values }
end
sanitized_attributes = sanitize_attributes(values)
associated_object =
if values.key?(:id)
relationship_type.to_s.singularize.camelcase.constantize.find(values[:id])
else
relationship_type.to_s.singularize.camelcase.constantize.new
end
associated_object.assign_attributes(sanitized_attributes)
if association_type == :to_one
_model.send("#{relationship_type}=", associated_object)
elsif association_type == :to_many
_model.send(relationship_type) << associated_object
end
# binding.pry
associated_object.save # TODO: save!
values.merge!(id: associated_object.id)
end
def sanitize_attributes(values)
(values[:attributes].presence || {}).reject { |attr, _value| attr.in?(%i(type)) }
end
end
|
require 'rails_helper'
RSpec.feature "タスク管理機能", type: :feature do
let(:user) { FactoryBot.create(:user) }
before do
# ユーザー作成
@user = (:user)
# サインイン
visit new_session_path
fill_in 'Email', with: user.email
fill_in 'Password', with: user.password
click_button 'Log in'
end
background do
FactoryBot.create(:label)
FactoryBot.create(:second_label)
FactoryBot.create(:third_label)
FactoryBot.create(:task, user_id: user.id,)
FactoryBot.create(:second_task, user_id: user.id)
FactoryBot.create(:third_task, user_id: user.id)
FactoryBot.create(:labellings)
FactoryBot.create(:second_labellings)
FactoryBot.create(:third_labellings)
end
scenario 'タスク一覧画面に遷移したら、作成済みのタスクが表示される' do
# Task.create!(title: 'test_task_01', content: 'testtesttest', expiration_out: '2019-08-16 12:00:00', user_id: user.id)
# Task.create!(title: 'test_task_02', content: 'samplesample', expiration_out: '2019-08-16 12:00:00', user_id: user.id)
# tasks_pathにvisitする(タスク一覧ページに遷移する)
visit tasks_path
# save_and_open_page
# visitした(到着した)expect(page)に(タスク一覧ページに)「testtesttest」「samplesample」という文字列が
# have_contentされているか?(含まれているか?)ということをexpectする(確認・期待する)テストを書いている
# expect(current_path).to have_content 'Factoryで作ったデフォルトのタイトル1'
# expect(current_path).to have_content 'Factoryで作ったデフォルトのタイトル2'
expect(page).to have_text /.*Factoryで作ったデフォルトのタイトル1.*Factoryで作ったデフォルトのタイトル2.*Factoryで作ったデフォルトのタイトル3.*/
end
scenario 'タスク登録画面で、必要項目を入力してcreateボタンを押したらデータが保存される' do
visit new_task_path
fill_in 'タイトル', with: 'test_task_05'
fill_in '内容', with: 'testtesttest05'
click_button '登録する'
task = Task.last
visit task_path(task.id)
#visit tasks_path
expect(page).to have_content 'test_task_05'
expect(page).to have_content 'testtesttest05'
end
scenario '任意のタスク詳細画面に遷移したら、該当タスクの内容が表示されたページに遷移する' do
Task.create!(title: 'test_task_06', content: 'testtesttest06', id: user.id, expiration_out: '2019-08-16 12:00:00', user_id: user.id)
visit task_path(id: user.id)
expect(page).to have_content 'test_task_06'
expect(page).to have_content 'testtesttest06'
end
scenario "タスク一覧のテスト" do
visit tasks_path
end
scenario "タスクが作成日時の降順に並んでいるかのテスト" do
# タスクが作成日時の降順に並んでいるかのテスト
# save_and_open_page この部分でViewを確認
visit tasks_path
expect(page).to have_text /.+タイトル2.+タイトル3.+/
end
scenario '終了期限順に並ぶこと' do
Task.create!(title: '終了期限テスト2', content: 'shuryoukigenntitle2', expiration_out: '2019-08-15', user_id: user.id)
Task.create!(title: '終了期限テスト1', content: 'shuryoukigenntitle1', expiration_out: DateTime.now, user_id: user.id)
Task.create!(title: '終了期限テスト3', content: 'shuryoukigenntitle3', expiration_out: '2019-08-15', user_id: user.id)
visit tasks_path
click_link '終了期限でソート'
expect(page).to have_text /.*終了期限テスト1.*終了期限テスト2.*終了期限テスト3.*/
end
scenario 'タイトル検索で任意の文字が含まれるタスクだけ表示される' do
visit tasks_path
fill_in 'title-search', with: 'タイトル2'
#save_and_open_page
click_button '絞り込み検索'
expect(page).to_not have_text /.+タイトル3.+タイトル1.+/
end
scenario '優先順位でソートしたら高中低の順に並ぶ' do
visit tasks_path
click_link '優先順位でソート'
expect(page).to have_text /.*タイトル2.*タイトル3.*タイトル1.*/
end
scenario 'ラベルをもつタスクをラベルで絞り込む' do
visit tasks_path
select "label1", from: 'label'
click_button '絞り込み検索'
expect(page).to have_text /.*タイトル1.*タイトル3.*/
end
end
|
class ItemImage < ApplicationRecord
belongs_to :item
mount_uploader :image, ItemImageUploader
validates :image, presence: true
end
|
# Write a program that converts a number to a string per the following rules:
# If the number contains 3 as a prime factor, output 'Pling'.
# If the number contains 5 as a prime factor, output 'Plang'.
# If the number contains 7 as a prime factor, output 'Plong'.
# If the number does not contain 3, 5, or 7 as a prime factor, simply return the string representation of the number itself.
require 'numbers_and_words'
class Raindrops
def convert(number)
represent = ''
if number % 3 == 0
represent += 'Pling'
end
if number % 5 == 0
represent += 'Plang'
end
if number % 7 == 0
represent += 'Plong'
end
if represent == ''
represent = number.to_i.to_words
end
puts represent
`say '#{represent}'`
end
end
drops = Raindrops.new.convert(28)
drops = Raindrops.new.convert(1755)
drops = Raindrops.new.convert(34)
drops = Raindrops.new.convert(961987)
drops = Raindrops.new.convert(17430461098673)
drops = Raindrops.new.convert(2398) |
class ChangeColumnToWants < ActiveRecord::Migration[5.2]
def up
change_column_default :wants, :count, 0
end
def down
change_column_default :wants, :count
end
end
|
require 'rubygems'
require 'nokogiri'
require 'zip'
require 'rubyXL/hash'
require 'rubyXL/generic_storage'
module RubyXL
class Parser
def self.parse(file_path, opts = {})
self.new(opts).parse(file_path)
end
# +:data_only+ allows only the sheet data to be parsed, so as to speed up parsing
# However, using this option will result in date-formatted cells being interpreted as numbers
def initialize(opts = {})
@data_only = opts.is_a?(TrueClass) || opts[:data_only]
@skip_filename_check = opts[:skip_filename_check]
end
def data_only
@data_only = true
self
end
def parse(file_path, opts = {})
# options handling
files = decompress(file_path)
wb = Workbook.new([], file_path)
fill_workbook(wb, files)
shared_string_file = files['sharedString']
unless shared_string_file.nil?
sst = shared_string_file.css('sst')
# According to http://msdn.microsoft.com/en-us/library/office/gg278314.aspx,
# these attributes may be either both missing, or both present. Need to validate.
wb.shared_strings.count_attr = sst.attribute('count').value.to_i
wb.shared_strings.unique_count_attr = sst.attribute('uniqueCount').value.to_i
# Note that the strings may contain text formatting, such as changing font color/properties
# in the middle of the string. We do not support that in this gem... at least yet!
# If you save the file, this formatting will be destoyed.
shared_string_file.css('si').each_with_index { |node, i|
wb.shared_strings.add(node.css('t').inject(''){ |s, c| s + c.text }, i)
}
end
#styles are needed for formatting reasons as that is how dates are determined
styles = files['styles'].css('cellXfs xf')
style_hash = Hash.xml_node_to_hash(files['styles'].root)
fills = files['styles'].css('fills fill')
wb.fills = fills.collect { |node| RubyXL::Fill.parse(node) }
colors = files['styles'].css('colors').first
if colors then
colors.element_children.each { |color_type_node|
wb.colors[color_type_node.name] ||= []
color_type_node.element_children.each { |color_node|
wb.colors[color_type_node.name] << RubyXL::Color.parse(color_node)
}
}
end
borders = files['styles'].css('borders border')
wb.borders = borders.collect { |node| RubyXL::Border.parse(node) }
fonts = files['styles'].css('fonts font')
wb.fonts = fonts.collect { |node| RubyXL::Font.parse(node) }
cell_styles = files['styles'].css('cellStyles cellStyle')
wb.cell_styles = cell_styles.collect { |node| RubyXL::CellStyle.parse(node) }
fill_styles(wb, style_hash)
wb.external_links = files['externalLinks']
wb.external_links_rels = files['externalLinksRels']
wb.drawings = files['drawings']
wb.drawings_rels = files['drawingsRels']
wb.charts = files['charts']
wb.chart_rels = files['chartRels']
wb.printer_settings = files['printerSettings']
wb.worksheet_rels = files['worksheetRels']
wb.macros = files['vbaProject']
wb.theme = files['theme']
sheet_names = files['app'].css('TitlesOfParts vt|vector vt|lpstr').children
files['workbook'].css('sheets sheet').each_with_index { |sheet_node, i|
parse_worksheet(wb, i, files['worksheets'][i], sheet_names[i].text,
sheet_node.attributes['sheetId'].value )
}
return wb
end
private
#fills hashes for various styles
def fill_styles(wb,style_hash)
###NUM FORMATS###
if style_hash[:numFmts].nil?
style_hash[:numFmts] = {:attributes => {:count => 0}, :numFmt => []}
elsif style_hash[:numFmts][:attributes][:count]==1
style_hash[:numFmts][:numFmt] = [style_hash[:numFmts][:numFmt]]
end
wb.num_fmts = style_hash[:numFmts]
wb.cell_style_xfs = style_hash[:cellStyleXfs]
wb.cell_xfs = style_hash[:cellXfs]
#fills out count information for each font, fill, and border
if wb.cell_xfs[:xf].is_a?(::Hash)
wb.cell_xfs[:xf] = [wb.cell_xfs[:xf]]
end
wb.cell_xfs[:xf].each do |style|
id = Integer(style[:attributes][:fontId])
wb.fonts[id].count += 1 unless id.nil?
id = style[:attributes][:fillId]
wb.fills[id].count += 1 unless id.nil?
id = style[:attributes][:borderId]
wb.borders[id].count += 1 unless id.nil?
end
end
# Parse the incoming +worksheet_xml+ into a new +Worksheet+ object
def parse_worksheet(wb, i, worksheet_xml, worksheet_name, sheet_id)
worksheet = Worksheet.new(wb, worksheet_name)
wb.worksheets[i] = worksheet # Due to "validate_workbook" issues. Should remove that validation eventually.
worksheet.sheet_id = sheet_id
dimensions = RubyXL::Reference.new(worksheet_xml.css('dimension').attribute('ref').value)
cols = dimensions.last_col
# Create empty arrays for workcells. Using +downto()+ here so memory for +sheet_data[]+ is
# allocated on the first iteration (in case of +upto()+, +sheet_data[]+ would end up being
# reallocated on every iteration).
dimensions.last_row.downto(0) { |i| worksheet.sheet_data[i] = Array.new(cols + 1) }
namespaces = worksheet_xml.root.namespaces
if @data_only
row_xpath = '/xmlns:worksheet/xmlns:sheetData/xmlns:row[xmlns:c[xmlns:v]]'
cell_xpath = './xmlns:c[xmlns:v[text()]]'
else
row_xpath = '/xmlns:worksheet/xmlns:sheetData/xmlns:row'
cell_xpath = './xmlns:c'
sheet_views_nodes = worksheet_xml.xpath('/xmlns:worksheet/xmlns:sheetViews/xmlns:sheetView', namespaces)
worksheet.sheet_views = sheet_views_nodes.collect { |node| RubyXL::SheetView.parse(node) }
col_node_set = worksheet_xml.xpath('/xmlns:worksheet/xmlns:cols/xmlns:col',namespaces)
worksheet.column_ranges = col_node_set.collect { |col_node| RubyXL::ColumnRange.parse(col_node) }
merged_cells_nodeset = worksheet_xml.xpath('/xmlns:worksheet/xmlns:mergeCells/xmlns:mergeCell', namespaces)
worksheet.merged_cells = merged_cells_nodeset.collect { |child| RubyXL::Reference.new(child.attributes['ref'].text) }
# worksheet.pane = worksheet.sheet_view[:pane]
data_validations = worksheet_xml.xpath('/xmlns:worksheet/xmlns:dataValidations/xmlns:dataValidation', namespaces)
worksheet.validations = data_validations.collect { |node| RubyXL::DataValidation.parse(node) }
#extLst
ext_list_node = worksheet_xml.xpath('/xmlns:worksheet/xmlns:extLst', namespaces)
unless ext_list_node.empty?
worksheet.extLst = Hash.xml_node_to_hash(ext_list_node.first)
else
worksheet.extLst = nil
end
#extLst
##legacy drawing##
legacy_drawing_node = worksheet_xml.xpath('/xmlns:worksheet/xmlns:legacyDrawing', namespaces)
unless legacy_drawing_node.empty?
worksheet.legacy_drawing = Hash.xml_node_to_hash(legacy_drawing_node.first)
else
worksheet.legacy_drawing = nil
end
##end legacy drawing
drawing_nodes = worksheet_xml.xpath('/xmlns:worksheet/xmlns:drawing', namespaces)
worksheet.drawings = drawing_nodes.collect { |n| n.attributes['id'] }
end
worksheet_xml.xpath(row_xpath, namespaces).each { |row|
unless @data_only
##row styles##
row_attributes = row.attributes
row_style = row_attributes['s'] && row_attributes['s'].value || '0'
worksheet.row_styles[row_attributes['r'].content] = { :style => row_style }
if !row_attributes['ht'].nil? && (!row_attributes['ht'].content.nil? || row_attributes['ht'].content.strip != "" )
worksheet.change_row_height(Integer(row_attributes['r'].value) - 1, Float(row_attributes['ht'].value))
end
##end row styles##
end
row.search(cell_xpath).each { |value|
#attributes is from the excel cell(c) and is basically location information and style and type
value_attributes = value.attributes
# r attribute contains the location like A1
cell_index = RubyXL::Reference.ref2ind(value_attributes['r'].content)
style_index = 0
# t is optional and contains the type of the cell
data_type = value_attributes['t'].content if value_attributes['t']
element_hash ={}
value.children.each { |node| element_hash["#{node.name()}_element"] = node }
# v is the value element that is part of the cell
if element_hash["v_element"]
v_element_content = element_hash["v_element"].content
else
v_element_content=""
end
if v_element_content == "" # no data
cell_data = nil
elsif data_type == RubyXL::Cell::SHARED_STRING
str_index = Integer(v_element_content)
cell_data = wb.shared_strings[str_index].to_s
elsif data_type == RubyXL::Cell::RAW_STRING
cell_data = v_element_content
elsif data_type == RubyXL::Cell::ERROR
cell_data = v_element_content
else# (value.css('v').to_s != "") && (value.css('v').children.to_s != "") #is number
data_type = ''
if(v_element_content =~ /\./ or v_element_content =~ /\d+e\-?\d+/i) #is float
cell_data = Float(v_element_content)
else
cell_data = Integer(v_element_content)
end
end
# f is the formula element
cell_formula = nil
fmla_css = element_hash["f_element"]
if fmla_css && fmla_css.content
fmla_css_content= fmla_css.content
if(fmla_css_content != "")
cell_formula = fmla_css_content
cell_formula_attr = {}
fmla_css_attributes = fmla_css.attributes
cell_formula_attr['t'] = fmla_css_attributes['t'].content if fmla_css_attributes['t']
cell_formula_attr['ref'] = fmla_css_attributes['ref'].content if fmla_css_attributes['ref']
cell_formula_attr['si'] = fmla_css_attributes['si'].content if fmla_css_attributes['si']
end
end
style_index = value['s'].to_i #nil goes to 0 (default)
worksheet.sheet_data[cell_index[0]][cell_index[1]] =
Cell.new(worksheet,cell_index[0],cell_index[1],cell_data,cell_formula,
data_type,style_index,cell_formula_attr)
cell = worksheet.sheet_data[cell_index[0]][cell_index[1]]
}
}
worksheet
end
def decompress(file_path)
dir_path = file_path
#ensures it is an xlsx/xlsm file
if (file_path =~ /(.+)\.xls(x|m)/) then
dir_path = $1.to_s
else
raise 'Not .xlsx or .xlsm excel file' unless @skip_filename_check
end
dir_path = File.join(File.dirname(dir_path), Dir::Tmpname.make_tmpname(['rubyXL', '.tmp'], nil))
#copies excel file to zip file in same directory
zip_path = dir_path + '.zip'
FileUtils.cp(file_path,zip_path)
MyZip.new.unzip(zip_path,dir_path)
File.delete(zip_path)
files = Hash.new
files['app'] = Nokogiri::XML.parse(File.open(File.join(dir_path,'docProps','app.xml'),'r'))
files['core'] = Nokogiri::XML.parse(File.open(File.join(dir_path,'docProps','core.xml'),'r'))
files['workbook'] = Nokogiri::XML.parse(File.open(File.join(dir_path,'xl','workbook.xml'),'r'))
files['workbook_rels'] = Nokogiri::XML.parse(File.open(File.join(dir_path, 'xl', '_rels', 'workbook.xml.rels'), 'r'))
if(File.exist?(File.join(dir_path,'xl','sharedStrings.xml')))
files['sharedString'] = Nokogiri::XML.parse(File.open(File.join(dir_path,'xl','sharedStrings.xml'),'r'))
end
unless @data_only
files['externalLinks'] = RubyXL::GenericStorage.new(File.join('xl', 'externalLinks')).load_dir(dir_path)
files['externalLinksRels'] = RubyXL::GenericStorage.new(File.join('xl', 'externalLinks', '_rels')).load_dir(dir_path)
files['drawings'] = RubyXL::GenericStorage.new(File.join('xl', 'drawings')).load_dir(dir_path)
files['drawingsRels'] = RubyXL::GenericStorage.new(File.join('xl', 'drawings', '_rels')).load_dir(dir_path)
files['charts'] = RubyXL::GenericStorage.new(File.join('xl', 'charts')).load_dir(dir_path)
files['chartRels'] = RubyXL::GenericStorage.new(File.join('xl', 'charts', '_rels')).load_dir(dir_path)
files['printerSettings'] = RubyXL::GenericStorage.new(File.join('xl', 'printerSettings')).binary.load_dir(dir_path)
files['worksheetRels'] = RubyXL::GenericStorage.new(File.join('xl', 'worksheets', '_rels')).load_dir(dir_path)
files['vbaProject'] = RubyXL::GenericStorage.new('xl').binary.load_file(dir_path, 'vbaProject.bin')
files['theme'] = RubyXL::GenericStorage.new(File.join('xl', 'theme')).load_file(dir_path, 'theme1.xml')
end
files['styles'] = Nokogiri::XML.parse(File.open(File.join(dir_path,'xl','styles.xml'),'r'))
files['worksheets'] = []
rels_doc = files['workbook_rels']
files['workbook'].css('sheets sheet').each_with_index { |sheet, ind|
sheet_rid = sheet.attributes['id'].value
sheet_file_path = rels_doc.css("Relationships Relationship[Id=#{sheet_rid}]").first.attributes['Target']
files['worksheets'][ind] = Nokogiri::XML.parse(File.read(File.join(dir_path, 'xl', sheet_file_path)))
}
FileUtils.rm_rf(dir_path)
return files
end
def fill_workbook(wb, files)
unless @data_only
wb.creator = files['core'].css('dc|creator').children.to_s
wb.modifier = files['core'].css('cp|last_modified_by').children.to_s
wb.created_at = files['core'].css('dcterms|created').children.to_s
wb.modified_at = files['core'].css('dcterms|modified').children.to_s
wb.company = files['app'].css('Company').children.to_s
wb.application = files['app'].css('Application').children.to_s
wb.appversion = files['app'].css('AppVersion').children.to_s
end
wb.shared_strings_XML = files['sharedString'].to_s
defined_names = files['workbook'].css('definedNames definedName')
wb.defined_names = defined_names.collect { |node| RubyXL::DefinedName.parse(node) }
wb.date1904 = files['workbook'].css('workbookPr').attribute('date1904').to_s == '1'
end
def self.attr_int(node, attr_name)
attr = node.attributes[attr_name]
attr && Integer(attr.value)
end
def self.attr_float(node, attr_name)
attr = node.attributes[attr_name]
attr && Float(attr.value)
end
def self.attr_string(node, attr_name)
attr = node.attributes[attr_name]
attr && attr.value
end
end
end
|
require 'spec_helper'
describe Curation do
let(:curation) { Curation.new }
it { should respond_to :image }
it { should respond_to :kind }
it { should respond_to :products }
it { should respond_to :retailers }
it { should respond_to :meta }
describe '#meta' do
subject { curation.meta }
its(:keys) { should match_array %w[ id title twitter_title email_body image kind social_image ]}
end
end
|
class RequestHandlersController < ApplicationController
def create
@post = Post.find_by id: params[:post_id]
if @post.photographer
flash[:alert] = t ".already_accepted_someone"
redirect_to root_path
return
end
@photographer = @post.candidates.find_by id: params[:photographer_id]
unless @photographer
flash[:alert] = t ".no_photographer"
redirect_to root_path
return
end
@post.photographer = @photographer
if @post.save
flash[:alert] = t ".accepted_request"
else
flash[:alert] = t ".some_thing_went_wrong"
end
redirect_to @post
end
end
|
module Backgrounded
attr_reader :delegate, :options
class Proxy
def initialize(delegate, options={})
@delegate = delegate
@options = options || {}
end
def method_missing(method_name, *args)
Backgrounded.handler.request(@delegate, method_name, args, @options)
nil
end
end
end
|
# DJ воркер. Создает и отправляет архив перерегистрации на email
class SessionDataSender < Struct.new(:id, :email)
def perform
@session = Session.find(id)
path = create_archive!
zip = path[/\/([\-\w]+\.zip)/, 1]
Mailer.delay.session_archive_is_ready(email, zip)
end
private
def create_archive!
path = "#{Rails.root}/public/archive-#{SecureRandom.hex(8)}.zip"
Zip::ZipFile.open(path, Zip::ZipFile::CREATE) do |z|
@session.users.each do |user|
dir = "#{I18n.transliterate(user.full_name)} (##{user.id})"
if report = user.reports.where(session_id: id).first
if report.materials.path
z.add "#{dir}/report.zip", report.materials.path
end
end
user.user_surveys.where(survey_id: @session.survey_ids).each do |us|
z.add "#{dir}/survey_#{us.id}.html", us.save_as_file(:html)
z.add "#{dir}/survey_#{us.id}.json", us.save_as_file(:json)
end
end
end
File.chmod 0655, path
path
end
end
|
class Department < ApplicationRecord
has_many :designations
validates :dep_code, presence: true, uniqueness: true
validates :dep_name, presence: true, uniqueness: true
end
|
class AddBeerIdToDrinks < ActiveRecord::Migration
def change
add_column :drinks, :beer_id, :integer
end
end
|
# frozen_string_literal: true
module PetsHelper
def pet_id
Pet.find(params[:id])
end
def pet_params
params[:status] = 'adoptable'
params.permit(:image, :name, :description, :age, :sex, :status)
end
end
|
# == Schema Information
#
# Table name: themes
#
# id :integer not null, primary key
# title :string(255)
# css_doc :text
# activated_at :datetime
# account_id :integer
# created_at :datetime not null
# updated_at :datetime not null
# background_image_file_name :string(255)
# background_image_content_type :string(255)
# background_image_file_size :integer
# background_image_updated_at :datetime
#
class Theme < ActiveRecord::Base
attr_accessible :activated_at, :css_doc, :title, :background_image
belongs_to :account
has_paper_trail
scope :active, where("activated_at is NOT NULL").order('activated_at DESC')
has_attached_file :background_image,
:storage => :s3,
:bucket => ENV['S3_BUCKET_NAME'],
:s3_credentials => {
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
},
:s3_protocol => :https,
:styles => { :large => "600x600>", :medium => "300x300>", :thumb => "100x100>" },
:path => ":account_subdomain/:class/:attachment/:id_partition/:style/:filename"
Paperclip.interpolates :account_subdomain do |attachment, style|
attachment.instance.account.subdomain
end
def activate!
self.update_attributes(:activated_at => Time.zone.now)
end
def self.active_theme
self.active.first
end
end
|
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
resource :tracers, only: %w[index create]
root "tracers#index"
end
|
module BadContactService
class IndexBadContact
prepend SimpleCommand
attr_reader :user, :params
def initialize(user = nil, params = {})
@user = user
@params = params
end
def call
BadContact.includes([:uploaded_file]).where(user: user).order(created_at: :desc)
end
end
end
|
class Action
attr_accessor :actor
attr_accessor :type
attr_accessor :amount
def self.debit(from:, amount:)
Action.new(from, 'debit', amount)
end
def self.credit(to:, amount:)
Action.new(to, 'credit', amount)
end
def initialize(actor, type, amount)
@actor = actor
@type = type
@amount = amount
end
# Compute the "diff" action between this action and other action
# Both actions must be of same type
def diff(other)
if @type != other.type
raise 'Both actions must be of same type.'
end
amount_diff = other.amount - @amount
if @type == 'credit'
if amount_diff < 0
Action.debit(from: @actor, amount: amount_diff.abs)
else
Action.credit(to: @actor, amount: amount_diff.abs)
end
else
if amount_diff > 0
Action.debit(from: @actor, amount: amount_diff.abs)
else
Action.credit(to: @actor, amount: amount_diff.abs)
end
end
end
def to_hash
return {
:who => @actor,
:type => @type,
:amount => @amount
}
end
end |
# encoding: UTF-8
# Copyright © Emilio González Montaña
# Licence: Attribution & no derivates
# * Attribution to the plugin web page URL should be done if you want to use it.
# https://redmine.ociotec.com/projects/advanced-roadmap
# * No derivates of this plugin (or partial) are allowed.
# Take a look to licence.txt file at plugin root folder for further details.
module AdvancedRoadmap
class ViewHooks < Redmine::Hook::ViewListener
render_on(:view_projects_show_sidebar_bottom, :partial => 'hooks/milestones')
render_on(:view_issues_sidebar_planning_bottom, :partial => 'hooks/milestones')
render_on(:view_issues_show_details_bottom, :partial => 'hooks/issues/show')
render_on(:view_layouts_base_html_head, :partial => 'hooks/stylesheet')
end
end
|
class BasicTrainee::UsersController < ApplicationController
layout "basic_application"
before_action :logged_in_user
before_action :load_user, only: %i(show edit update)
def show; end
def edit; end
def update
if @user.update_attributes user_params
flash[:success] = t "controllers.users.update_user"
redirect_to root_path
else
render :edit
end
end
private
def user_params
params.require(:user).permit :name, :email, :password, :address,
:password_confirmation, :phone_number
end
def load_user
@user = User.find_by id: params[:id]
return if @user
flash[:danger] = t "controllers.users.user_not_found"
redirect_to root_path
end
end
|
desc 'This task is called by the Heroku scheduler add-on'
task pay_participants: :environment do |t, args|
Participation.where(paid: false, accepted: true).each do |participation|
return if participation.rated
PayParticipantsWorker.perform_async(participation.id)
end
end
|
class OrdersController < ApplicationController
before_action :authenticate_user!
before_filter :set_order, :except => [:create, :index, :new, :assign_shipped, :add_shipping_confirmation, :show]
def index
@campaign = Campaign.friendly.find(params[:campaign_id])
@orders = @campaign.orders
end
def show
@order = Order.find(params[:id])
end
def new
@campaign = Campaign.friendly.find(params[:campaign_id])
@order = @campaign.orders.new
@cart = session[:cart]
end
def create
@campaign = Campaign.friendly.find(params[:campaign_id])
@cart = session[:cart]
@order = @campaign.order |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.