text stringlengths 10 2.61M |
|---|
# talkblocks.rb
# Groups vocab into blocks.
# Vocab from talktext.rb.
module TalkBlocks
def hi
type_puts(say_hello)
type_puts(ask_name)
end
def greet_human(human)
type_puts(greet(human))
type_puts(nice_face(human))
type_puts(ellipsis)
type_puts(buzz(human))
type_puts(ask_if_h... |
module Lugg
# An object representing a command line swith with certain behaviour. The
# Runner applies switches to its own internal `OptionParser` object to build
# the CLI and provide querying functionality.
#
# @see Runner
class Switch
@queries = []
# Define a new Switch object and add it to the ... |
require File.expand_path("../helper", __FILE__)
describe 'LIVE testwiki instance' do
before(:all) do
@wiki = Localwiki::Client.new 'ec2-54-234-151-52.compute-1.amazonaws.com',
ENV['localwiki_client_user'],
ENV['localwiki_client_apikey']
end
... |
class Gperf < Package
name 'gperf'
desc "GNU gperf is a perfect hash function generator"
homepage "https://www.gnu.org/software/gperf/"
url "http://ftp.gnu.org/pub/gnu/gperf/gperf-${version}.tar.gz"
release version: '3.1', crystax_version: 2
build_copy 'COPYING'
build_options use_cxx: true, copy_instal... |
require 'digest'
module OneDoc
class Document
def initialize(target)
@target = target
end
def namespace
end
def class
end
def module
end
def files
[]
end
def doc_for_file(file)
nil
end
def classes_in_file(file)
[]
end
def modu... |
#!/usr/bin/env ruby
require "dns"
if ARGV.empty?
get_dns
exit
end
case ARGV.first
when 'list'
res = `networksetup -listallnetworkservices`
res_copy = res.dup
res_copy.prepend "# Network Services:\n"
res_copy = res_copy.split("\n").map.with_index do |name, index|
if index > 1
"- #{name}"
e... |
class AddGisSupport < ActiveRecord::Migration
def change
remove_column :service_stations, :latitude
remove_column :service_stations, :longitude
add_column :service_stations, :location, :point, geographic: true
end
end
|
class AccountUser < ApplicationRecord
belongs_to :account
belongs_to :user
ACCOUNT_USER_ROLES = ['Owner','Admin','Editor']
validates :role, inclusion: { in: ACCOUNT_USER_ROLES, message: "%{value} is not a valid role" }
before_validation :assign_role
private
def assign_role
self.role ||= 'Editor'
... |
# frozen_string_literal: true
module Vedeu
module Groups
# Allows the storing of view groups.
#
# @api private
#
class Repository < Vedeu::Repositories::Repository
null Vedeu::Groups::Group
real Vedeu::Groups::Group
end # Groups
class Group
repo Vedeu::Groups::Repo... |
class AnimUrlCreate < ActiveRecord::Migration
def change
create_table :urls do |t|
t.text :url, null: false
t.string :animurl, null: false
t.timestamps null: false
end
create_table :adjectives do |t|
t.string :adjective, null: false
t.string :type, null: false
t.time... |
class UserSport < ApplicationRecord
belongs_to :user
belongs_to :sport
validates_uniqueness_of :sport_id, :scope => :user_id
end
|
# -*- coding: utf-8 -*-
class Category < ActiveRecord::Base
acts_as_nested_set
validates :name, :presence => true
default_scope order("created_at ASC")
include ModelRemovable
def self.import_from_yaml(file)
text = file.read
text = text.gb2312_to_utf8 if !text.utf8?
hash = YAML.load(... |
# Monkey-Patch Ruby's existing Array class to add your own custom methods
class Array
def span
if self.length > 0
maximum = self.max
mininimum = self.min
diference = maximum - mininimum
return diference
else
return nil
end
end
... |
class Artist < ActiveRecord::Base
attr_accessible :name, :bio, :image
has_many :videos, :foreign_key => 'artist_id'
scope :order_by, lambda { |o| {:order => o} } #For alphabetical order
def to_param
"#{id} #{name}".parameterize
end
def self.create_new_artist(name)
create(:name => name)
end
end
|
module Dexter
class LogParser
include Logging
REGEX = /duration: (\d+\.\d+) ms (statement|execute [^:]+): (.+)/
def initialize(logfile, collector)
@logfile = logfile
@collector = collector
end
private
def process_entry(query, duration)
@collector.add(query, duration)
... |
input_hash = {
:name => 'test-server',
:flavor => '123'
}
output_hash = {
'name' => 'test-server',
'flavor' => '123'
}
Shindo.tests('Fog::StringifyKeys', 'core') do
tests('keys') do
tests('stringifies symbols') do
returns(output_hash) {
Fog::StringifyKeys.stringify(input_hash)
}
... |
# The business logic for sources.
#
# This code is part of the Stoffi Music Player Project.
# Visit our website at: stoffiplayer.com
#
# Author:: Christoffer Brodd-Reijer (christoffer@stoffiplayer.com)
# Copyright:: Copyright (c) 2015 Simplare
# License:: GNU General Public License (stoffiplayer.com/license)
class S... |
require File.expand_path(File.dirname(__FILE__) + '/../acceptance_helper')
feature "Dashboard Themes" do
background do
log_in_as_administrator
@theme = FactoryGirl.create(:theme)
end
scenario "Create a Theme" do
curator = FactoryGirl.create(:user, :editor)
visit new_dashboard_theme_path
... |
require 'spec_helper'
describe "UserFriendship" do
self.use_transactional_fixtures = false
let(:user) { Factory(:user) }
let(:user2) { Factory(:user) }
describe "POST create" do
it "user accept friendship", :js => true do
user2.be_friends_with(user)
login_as(user, :scope => :user)
visit ... |
class StoreImage < ActiveRecord::Base
# Associations
#----------------------------------------------------------------------------
belongs_to :store
# Attached Image
#----------------------------------------------------------------------------
has_attached_file :image, :styles => { :medium => "medium"... |
class Enterprise < ApplicationRecord
include EnterpriseValidation
include EnterpriseRelation
extend FriendlyId
friendly_id :company, use: :slugged
def should_generate_new_friendly_id?
new_record? || company_changed?
end
def normalize_friendly_id(input)
input.to_s.to_slug.normalize(transliteratio... |
# coding: utf-8
=begin
require 'spec_helper'
describe Chanko::Helper, :type => :helper do
include Chanko::Helper
it "hello" do
unit(:sample).hello.should == "hello"
end
end
=end
|
class Photo < ApplicationRecord
validate :title_validation, :filename_validation
belongs_to :user
private
def title_validation
if title.empty?
errors.add('タイトル', "を入力してください")
end
if title.length > 30
errors.add('タイトル', "は30文字以内で入力してください")
end
end
def filename_validation
i... |
class Api::V1::PriceRecordsController < Api::V1::BaseController
before_action :set_price_record, only: [:show, :update, :destroy]
def index
json_response(PriceRecord.all.paginate(page: params[:page], per_page: 20))
end
def show
json_response(@price_record)
end
def create
price_record = PriceR... |
class AssayMessageProcessor
include PatientProcessor
def process(message)
message = ApplicationHelper.to_symbols(message)
Shoryuken.logger.info "========================== Incoming message: #{message.to_json} \n"
begin
specimen = NciMatchPatientModels::Specimen.query_latest_tissue_specimen_by_p... |
class Topic < ActiveRecord::Base
before_create :delete_last_topic
paginates_per 10
belongs_to :board
has_many :posts
validates :topic_name, presence: true, length: { maximum: 100 }
validates :description, presence: true, length: { maximum: 500 }
validates :topic_image, presence: true
has_attached_file ... |
require 'rails_helper'
RSpec.describe V1::Services::Create do
subject(:post_action) { post '/api/v1/services', params: params }
let(:params) do
{
vin: vin,
service: { start_date: start_date }
}
end
before { post_action }
context 'when params are valid' do
let(:start_date) { Time.cu... |
class BoardSerializer
include JSONAPI::Serializer
attributes :id, :board_properties
end
|
require "console_utils/request_utils/requester"
module ConsoleUtils::RequestUtils #:nodoc:
class Exap < Requester
INSPECT_FORMAT = "<Local: %s (%s)>".freeze
ConsoleUtils.request_methods.each do |request_method|
class_eval <<~RUBY, __FILE__, __LINE__ + 1
def #{request_method}(url, *args)
... |
class YellowCard < ApplicationRecord
belongs_to :start_appearance, optional: true
belongs_to :substitue_appearance, optional: true
belongs_to :referee_match
has_one :red_card
end
|
Rails.application.routes.draw do
resources :coupons, only: [:show, :index, :new, :create]
end
|
require 'vanagon/component/source'
describe "Vanagon::Component::Source" do
let(:klass) { Vanagon::Component::Source }
describe ".source" do
let(:unrecognized_uri) { "abcd://things" }
let(:unrecognized_scheme) { "abcd" }
let(:invalid_scheme) { "abcd|things" }
let(:public_git) { "git://github.com/... |
class AddDefaultValueToUsers < ActiveRecord::Migration[5.1]
def change
change_column :users, :status, :boolean, default: false
change_column :users, :is_admin, :boolean, default: false
change_column :users, :point, :integer, default: 0
end
end
|
class Api::V1::BaseController < ActionController::Base
# before_filter :authenticate_user_from_token!
# skip_before_filter :verify_authenticity_token,:if => Proc.new { |c| c.request.format == 'application/json' }
respond_to :json
private
#https://gist.github.com/josevalim/fb706b1e933ef01e4fb6
def authenticate... |
class Post < ActiveRecord::Base
mount_uploader :image, ImageUploader
validates_presence_of :content
end
|
class Api::V1::UsersController < Api::V1::BaseController
skip_before_action :authenticate_token?
def create
user = User.new(user_params)
token = SecureRandom.base58(24)
if User.find_by(:token => token).nil?
token = SecureRandom.base58(24)
end
user.token = token
if user.save
re... |
require_relative "test_helper"
require_relative "../lib/transaction_repository"
class TransactionRepositoryTest < Minitest::Test
def test_it_exists
parent = mock("parent")
tr = TransactionRepository.new("./test/fixtures/transactions_fixture.csv", parent)
assert_instance_of TransactionRepository, tr
e... |
class Email
define_method(:initialize) do |attributes|
@email = attributes.fetch(:email)
end
@@all_emails = []
define_method(:save) do
@@all_emails.push(self)
end
define_singleton_method(:all) do
@@all_emails
end
define_singleton_method(:clear) do
@@all_emails.clear()
end
end
|
json.array!(@dividends) do |dividend|
json.extract! dividend,
:id,
:year,
:age,
:amount
json.url insurance_dividend_url(dividend.insurance, dividend, format: :json)
end
|
class IconsController < ApplicationController
before_action :set_icon, only: [:show, :edit, :update, :destroy]
# GET /icons
# GET /icons.json
def index
@icons = Icon.all
end
# GET /icons/1
# GET /icons/1.json
def show
end
# GET /icons/new
def new
@icon = Icon.new
end
# GET /icon... |
class Stage < ActiveRecord::Base
validates :url, presence: true, uniqueness: true
before_create :generate_uuid
has_one :recent_deploy, -> { where.not finished_at: nil }, class_name: 'Deploys::Recent', dependent: :destroy
has_one :upcoming_deploy, -> { where finished_at: nil }, class_name: 'Deploys::Upcoming',... |
require 'rails_helper'
describe Product do
describe '#create' do
it "値が全て存在すれば登録できる" do
category = create(:category)
product = build(:product, category_id: category.id)
expect(product).to be_valid
end
it "nameが空では登録できないこと" do
product = build(:product, name: nil)
product.vali... |
class RelationshipsController < ApplicationController
before_action :logged_in_user
def create
@user = User.find_by id: params[:followed_id]
return unless @user
follow @user
end
def destroy
relationship = Relationship.find_by(id: params[:id])
return unless relationship
@user = relation... |
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel... |
require 'sumac'
# make sure it exists
describe Sumac::LocalObject::InstanceMethods do
# #expose_singleton_method
# functional test
example do
c = Class.new do
include Sumac::Expose
end
i = c.new
i.expose_singleton_method(:a,:b,'c')
expect(i.exposed_singleton_methods).to eq([:a,:b,:c])
... |
require 'rails_helper'
feature 'clients have categories' do
let(:department) { create :department }
let(:user) { create :user, department: department }
before do
FeatureFlag.create!(flag: 'categories', enabled: true)
login_as user
end
describe 'setting and sorting categories', js: true do
let!(... |
# frozen_string_literal: true
require_relative 'lib/fast_premailer/version'
Gem::Specification.new do |spec|
spec.name = 'fast_premailer'
spec.version = FastPremailer::VERSION
spec.authors = ['Yuri Demin', 'GroupPrice dev team']
spec.email = ['yuri.demin@groupprice.ru']
spec.su... |
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Actions::CreateReservation do
let(:user) { create :user }
let(:event) { create :event }
let(:event_2) { create :event }
let(:ordered_tickets) { { avoid_one: 1 } }
let(:instance) { described_class.new(user: user,... |
class CreateRecipes < ActiveRecord::Migration[5.2]
def change
create_table :recipes do |t|
t.string :name, null: false, limit: 50
t.text :description, null: false, limit: 500
t.bigint :user_id, null: false
t.integer :minutes_to_make, ... |
1.upto(102) do |id|
file_contents = File.read("scraped/#{id}")
doc = Boilerpipe::SAX::BoilerpipeHTMLParser.parse(file_contents)
# merge adjacent blocks with equal text_density
::Boilerpipe::Filters::SimpleBlockFusionProcessor.process doc
# merge text blocks next to each other
::Boilerpipe::Filters::BlockP... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/xenial64"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_che... |
require 'rails_helper'
RSpec.describe Comment, type: :model do
let!(:user) {User.create!(name: 'VanVan',location: 'Cuba',username: 'aquinomas',password: 'aquinomas')}
let!(:question) {Question.create(title: "Fake answer", body: "Some text", user: user)}
let!(:answer) {Answer.create( body: "Some text", question: ... |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
#set_session_for users(:job_creating_rubyist)
describe UserSessionsController do
describe 'GET new' do
context 'logged in' do
before do
set_session_for users(:loyal_rubyist)
get :new
end
it 'should redirect to... |
namespace :easy do
namespace :reference_data do
desc "Refreshes reference data values for the current environment. Pass the wrap_in_transaction flag to refresh in a transaction."
task :refresh, [:wrap_in_transaction] => :environment do |_task, args|
Easy::ReferenceData.load_files(wrap_in_transaction: ar... |
require 'rails_helper'
RSpec.describe Tag, type: :model do
it "should be able to create a Tag model given a name for it" do
tag = Tag.create!(name: "outdoors")
expect(tag).to respond_to(:name)
end
end
|
# frozen_string_literal: true
class Runner
def initialize(file_path)
@file_path = file_path
end
def run_logs_filtering
validate_file
print_results
end
private
attr_reader :file_path
def parse_file
FileParser.new(file_path).parse_file_data
end
def collect_data
DataCollector.ne... |
class Servicereq < ActiveRecord::Base
validates :type, :desc, :status, presence:true
belongs_to :user
belongs_to :client
end
|
class RecordAssignment < ActiveRecord::Base
belongs_to :course
belongs_to :record_group
has_many :record_batch_assignments,:dependent=>:destroy
validates_presence_of :record_group_id
accepts_nested_attributes_for :record_batch_assignments, :allow_destroy => true
def validate
if self.add_for_future==fal... |
class AddEmailEnableColoumnToStudent < ActiveRecord::Migration
def self.up
add_column :students, :is_email_enabled, :boolean,:default=>true
end
def self.down
remove_column :students, :is_email_enabled
end
end
|
class AddBandsToConcerts < ActiveRecord::Migration
def change
add_column(:concerts, :bandname, :string)
end
end
|
class Season < Sequel::Model
plugin :validation_helpers
one_to_many :season_match_groups
one_to_many :season_comments
many_to_many :members, :class => :User, :left_key => :season_id, :right_key => :user_id, :join_table => :users_seasons
many_to_one :owner, :class => :User, :key => :owner_id
def validate
... |
class Log < ApplicationRecord
has_many :captures, dependent: :destroy
def self.create_from_raw_json(rawjson)
Log.create(time: rawjson['timestamp'].to_s.gsub('\u0000', ''),
status: rawjson['eventid'],
protocol: rawjson['protocol'],
ip_address: rawjson['src_ip'],
... |
class FontLakkiReddy < Formula
head "https://github.com/google/fonts/raw/main/ofl/lakkireddy/LakkiReddy-Regular.ttf", verified: "github.com/google/fonts/"
desc "Lakki Reddy"
homepage "https://fonts.google.com/specimen/Lakki+Reddy"
def install
(share/"fonts").install "LakkiReddy-Regular.ttf"
end
test do
... |
oauth_definitions = AppConfig[:authentication_sources].find_all { |as|
as[:model] == 'ASOauth'
}
raise "OmniAuth plugin enabled but no definitions provided =(" unless oauth_definitions.any?
# GOOGLE STRATEGY FOR TESTING [DO NOT USE IN PROD UNLESS YOU MEAN TO]
def google_oauth_enabled?
ENV.has_key?('GOOGLE_CLIENT_I... |
class MailIdDefinitionsController < ApplicationController
# GET /mail_id_definitions
# GET /mail_id_definitions.json
def index
@mail_id_definitions = MailIdDefinition.paginate(:page => params[:page]).order('id DESC')
respond_to do |format|
format.html # index.html.erb
format.json { render jso... |
# A publish intent is sent to the Publishing API to indicate that a document is
# due to be published at a given set of routes at a given time.
#
# See [content_store](https://github.com/alphagov/content-store) for more
# details on publish intents.
class PublishingApiPresenters::PublishIntent
attr_reader :item
de... |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
def logged_in?
redirect_to login_path, notice: 'You must log in to access this page' unless session[:user_id]
end
def logged_in_as_admin?
redirect_to root_path, notice: 'You do not ... |
class Tank < ActiveRecord::Base
attr_accessible :fake, :game_id, :player_id, :position
belongs_to :game
belongs_to :player
validates :game, :position, :player, presence: true
validates :position, inclusion: {in: [1, 2, 3]}
end
|
require 'spec_helper'
describe TeamsController do
describe "GET /teams" do
it 'routes to teams#index' do
get('/teams').should route_to(controller: 'teams', action: 'index')
end
end
describe "POST /teams" do
it 'routes to teams#create' do
post('/teams').should route_to(controller: 'teams... |
# frozen_string_literal: true
module SidekiqUniqueJobs
#
# Base class for all exceptions raised from the gem
#
# @author Mikael Henriksson <mikael@zoolutions.se>
#
class UniqueJobsError < ::RuntimeError
end
# Error raised when a Lua script fails to execute
#
# @author Mikael Henriksson <mikael@zoo... |
class Estado < ActiveRecord::Base
belongs_to :pais
has_one :factura
has_many :personas
end
|
class CreateFormulaFixtureHeats < ActiveRecord::Migration[5.1]
def change
create_table :formula_fixture_heats do |t|
t.integer :heat_number, null: false
t.integer :race_number, null: false
t.string :slug, null: false
t.references :formula_fixture, foreign_key: true, null: false
t.str... |
require 'test_helper'
class UrlCreationTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers
setup do
Settings.enable_logins = true
Settings.enable_url_pushes = true
Rails.application.reload_routes!
@luca = users(:luca)
@luca.confirm
sign_in @luca
end
te... |
=begin
Building and sorting an array. Write a program that asks you to type as many words as you want (one word per line,
continuing until you just press Enter on an empty line), and then repeat the words back to you in alphabetical order.
=end
puts 'Type some words and I\'ll sort them for you.'
words = []
while true
... |
# frozen_string_literal: true
FactoryBot.define do
factory :booking do
user_id { 1 }
room_id { 1 }
date { '2021-03-21' }
start_time { '09:00' }
end_time { '09:30' }
end
end
|
class Campu < ActiveRecord::Base
validates :name, presence: true, allow_blank: false
has_many :faculties, dependent: :destroy
has_many :graduations, dependent: :destroy
end
|
class Ability
include CanCan::Ability
def initialize(user)
if user
can :access, :rails_admin
can :dashboard
can :index, :all
can :show, :all
can :export, :all
can :history, :all
can :manage, Admin
end
end
end
|
ROM::SQL.migration do
change do
create_table :car_parts do
primary_key :id
column :name, String, null: false
column :mark, String, null: false
column :price, Integer, null: false
end
end
end
|
module LegalServices::JourneyHelper
def lot_full_description(lot)
"Lot #{lot.number} - #{lot.description}"
end
def lot_legal_services(lot)
"Lot #{lot.number} legal services"
end
def region_name(name)
name.split('(')[0].strip
end
end
|
class AmazonDVDGrazer < AmazonGrazer
def self.top_url
'http://www.amazon.co.uk/s/ref=s9_al_bw_srch?rh=n%3A283926%2Cp_69%3A1y-%2Cp_n_binding_browse-bin%3A383381011&page=1&bbn=283926&rw_html_to_wsrp=1&pf_rd_m=A3P5ROKL5A1OLE&pf_rd_s=center-3&pf_rd_r=1T98JGJZQWGH3QMR0GG0&pf_rd_t=101&pf_rd_p=509179087&pf_rd_i=573412'... |
class ChangePlayerClassSpellsTableName < ActiveRecord::Migration
def change
rename_table :player_class_spells, :player_classes_spells
end
end
|
describe "Dog" do
# https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let
it 'instantiates a new dog' do
expect(1).to eq(1)
end
it 'has a name' do
expect(1).to eq(1)
end
it "is able to bark" do
expect(1).to eq(1)
end
end
|
class EventProvider < ApplicationRecord
enum status: [:confirmed, :not_going, :maybe]
belongs_to :meal_event
belongs_to :provider
belongs_to :contract
end
|
require 'rails_helper'
RSpec.describe User, type: :model do
it "has withdrawls" do
clark = User.create!(name: "Clark", address: "123 Main", phone_number: "917", balance: 50)
withdrawls = Withdrawl.create!(user: clark, amount: 10)
expect(clark.withdrawls).to eq([withdrawls])
end
it "has lodgements" ... |
class AddAttributesToEmployers < ActiveRecord::Migration[5.1]
def change
add_column :employers, :company_name, :string
add_column :employers, :contact_info, :string
add_column :employers, :image, :string
add_column :employers, :employer_website, :string
add_column :employers, :employer_bio, :text
... |
require 'spec_helper'
describe User do
# Migrations
it { should have_db_column(:email) }
# Validations
it { should validate_presence_of(:email) }
it { should validate_presence_of(:hashed_password) }
# Associations
it { should have_many(:playlists) }
# Indexes
xit { should have_index(:playlist) }... |
# coding: utf-8
require './pieces'
class Board
attr_accessor :board
BACK_ROW = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook]
def self.build_board
Array.new(8) { Array.new(8, nil)}
end
def initialize(board = self.class.build_board, duped = false)
@board = board
populate_board if !d... |
# -*- mode: ruby -*-
#
VAGRANT_DEFAULT_PROVIDER="virtualbox"
Vagrant.configure("2") do |config|
# Configure base
config.vm.box = 'centos/7'
config.ssh.forward_agent = true
# Vault Development
config.vm.define :vault do |vault|
vault.vm.hostname = "vault"
vault.vm.network :private_network... |
module Refinery
module TeamMembers
module Admin
class TeamMembersController < ::Refinery::AdminController
crudify :'refinery/team_members/team_member',
:title_attribute => 'name'
private
# Only allow a trusted parameter "white list" through.
def team_member... |
class Array
#return true if all array elements are empty, false otherwise
def all_empty?
self.all? { |element| element.to_s.empty? }
end
#return true if all array el are same, false otherwise
def all_same?
self.all?{ |element| element == self[0] }
end
#return true if all array el are empty
def any_empt... |
class ArticleForm
include Virtus.model
include ActiveModel::Model
attribute :id, String
attribute :text, String
attribute :status, Integer
validates_presence_of %i(
id
text
status
)
end
|
require "tephue/version"
require "tephue/command"
require "tephue/bcrypt_hasher"
require "tephue/configuration"
require "tephue/entity"
require "tephue/handler"
require "tephue/repository"
module Tephue
def self.config
@config ||= Configuration.new
end
def self.config=(value)
@config = value
end
de... |
class RenameColumnsToTaskboards < ActiveRecord::Migration
def change
rename_column :taskboards, :new, :un_assigned
rename_column :taskboards, :in_progress, :assigned
rename_column :taskboards, :development_completed, :tech_spec
rename_column :taskboards, :qa, :development
rename_column :taskboards... |
class User < ActiveRecord::Base
has_many :user_groups
# 新規ユーザのレコードを作成する際にデフォルト値を設定
after_initialize :set_default, if: :new_record?
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:r... |
require "test_helper"
class CategoryTest < ActiveSupport::TestCase
setup do
@category = categories(:food)
end
test "valid category" do
assert @category.valid?
end
test "invalid without description" do
@category.description = nil
refute @category.valid?
assert @category.errors[:descripti... |
# frozen_string_literal: true
# rubocop:disable Lint/HandleExceptions
begin
require 'jiji/test/mock/mock_securities'
rescue LoadError
end
# rubocop:enable Lint/HandleExceptions
module Jiji::Model::Securities
class SecuritiesFactory
include Jiji::Errors
def initialize
@available_securities = {}
... |
class Attendance < ApplicationRecord
belongs_to :user
belongs_to :event
after_create :send_notif_email, if: -> { Rails.env.production? }
def send_notif_email
UserMailer.attendance_notif_email(self).deliver_now
end
end
|
# -*- coding: utf-8 -*-
require "moji"
require "active_support/time"
require "ja_to_time/version"
class String
def ja_to_time
self.zen_to_han.remove_wday.replace_date_sep.move_up_time
end
def zen_to_han
::Moji.zen_to_han(self)
end
def replace_date_sep
date = %w(年 月 日).inject(self) do |date, s... |
require 'csv'
module FileSplitter
class CsvSplit
def initialize(file, rows, output_dir = false)
@file = file
@file_name = File.basename(@file, ".*")
@file_path = File.dirname(@file)
@rows = rows
@header = true
@current_row = 1
@total_rows = total_rows
@output_dir =... |
module DynaStruct
module Modifiable
def <<(args)
add_attributes args if args.kind_of?(Hash)
self
end
def remove(*vars)
result = vars.map do |var|
remove_singleton_method(var.to_s) if singleton_method_defined?(var.to_s)
remove_singleton_method("#{var}=") if singleton_meth... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.