text stringlengths 10 2.61M |
|---|
module KegHelper
def reset_form_button
"<button class='btn' data-reset-form='true'><i class='fa fa-times'></i> <span class='hidden-phone'>#{t("reset_form")}</span></button>".html_safe
end
def pretty_photo(image, image_style, image_params = {})
link_to(image_tag(image.attachment.url(image_style), image_p... |
require 'rasem'
require 'phenoscaperb'
require 'awesome_print'
require_relative 'simple_nexml.rb'
require 'byebug'
class FishTank
BASE = 'http://purl.obolibrary.org/obo/'
# TODO: move to file
QUALITIES = [
'PATO_0000052', # shape
'PATO_0000117', # size
'PATO_0000014', # color
'PATO_0000070', ... |
require 'delegate'
# = PythonConfig
# Class for parsing and writing Python configuration files created by the
# ConfigParser classes in Python. These files are structured like this:
# [Section Name]
# key = value
# otherkey: othervalue
#
# [Other Section]
# key: value3
# otherkey = value4
#
# Lead... |
#!/usr/bin/env ruby
# Copyright 2017 Se Kyeong Cheon
# 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 app... |
module FileUploadCache
module CachedAttributes
extend ActiveSupport::Concern
module ClassMethods
def cached_file_for(field)
attr_accessor :"#{field}_cache_id", :"cached_#{field}"
define_method "#{field}_with_cache=" do |value|
instance_variable_set("@#{field}_original", value... |
class Member < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :invitable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :albums
has_many :groups
has... |
class Admin::ProductsController < Admin::BaseController
def index
@categories = Category.roots.includes(children: :children)
.as_json(include: {children: {include: :children}})
@search = ProductSearch.new(search_params)
@products = @search.results.includes(:product_attachments, ... |
module Selenium::WebDriver::Find
def find_element_without_no_element_error(*args)
find_element(*args)
rescue Selenium::WebDriver::Error::NoSuchElementError
nil
end
def find_elements_without_no_element_error(*args)
find_elements(*args)
rescue Selenium::WebDriver::Error::NoSuchElementError
nil
... |
module Eneroth
module ViewportResizer2
Sketchup.require "#{PLUGIN_ROOT}/picker"
# Tool for picking entity or two points, later used to define a ratio.
#
# @example
# PickRatioTool.activate { |callback| p callback }
class PickRatioTool
include Picker
# Status text for first pick... |
Gretel::Crumbs.layout do
crumb :groups_index do
link I18n.t('groups.all_discussion'), {:controller=>"groups",:action=>"index"}
end
crumb :groups_new do
link I18n.t('groups.create_new_group'), {:controller=>"groups",:action=>"new"}
parent :groups_index
end
crumb :groups_create do
link I18n.t... |
class TournamentValidator < ActiveModel::Validator
def validate(record)
if (record.start_date.nil? || record.start_date.to_date <= Date.current)
record.errors.add :base, message: "토너먼트 생성은 내일 이후의 일정으로만 생성 가능합니다."
elsif invalid_tournament_time?(record.tournament_time)
record.errors.add :base, messa... |
require 'rspec'
require_relative 'word_analysis'
describe WordAnalysis do
it "takes in text" do
input = WordAnalysis.new('HERE IS SOME DUMB TEXT')
expect(input.text).to eq('HERE IS SOME DUMB TEXT')
end
it "counts how many words are in the text" do
input = WordAnalysis.new('HERE IS SOME DUMB TEXT WI... |
class CitySerializer < ActiveModel::Serializer
attributes :id, :name, :state_id
def id
object._id.to_s
end
def state_id
object.state_id.to_s
end
end
|
class ChangeTimePubDateOfTopics < ActiveRecord::Migration[5.0]
def change
change_column(:topics, :pubDate, :time)
end
end
|
class Business < ActiveRecord::Base
belongs_to :category
has_many :reviews
validates :business_name, presence: true
validates :category_id, presence: true
def business_name=(s)
super s.titleize
end
end
|
require 'spec_helper'
require 'legion/transport/queue'
RSpec.describe Legion::Transport::Queue do
it 'is a class' do
expect(Legion::Transport::Queue).to be_a Class
end
let(:klass) { Legion::Transport::Queue }
it 'can init' do
expect { klass.new('test') }.not_to raise_error
expect { klass.new('test... |
module Ahoy
module Stores
class BaseStore
def initialize(options)
@options = options
end
def track_visit(options)
end
def track_event(name, properties, options)
end
def visit
end
def authenticate(user)
@user = user
if visit and vis... |
class Style < ApplicationRecord
has_many :shoe_models
end
|
require 'rails_helper'
RSpec.describe QuestionsController, type: :controller do
context '#show' do
describe 'when params choice is' do
it 'LAST_YEAR and return' do
response = get :index, params: { choice: Question.ranges[0] }
expect(response.status).to eq(200)
end
it 'LAST_MONT... |
# # Default to assuming our server is a 1gb instance
system_total_mem_mb = '1024'
unless node['memory']['total'].nil?
system_total_mem_mb = (node['memory']['total'].gsub(/kB/, '').to_i / 1024).round
end
node.default['redisio']['default_settings']['maxmemorypolicy'] = 'allkeys-lru'
node.default['redisio']['default_se... |
class EventsController < ApplicationController
def reserve
event = Event.find_by(event_params)
event.participant_id = current_user.id
if event.save
redirect_to user_events_path(current_user), notice: 'Success Reservation'
else
falsh.now[:alert] = event.errors.full_messages
render re... |
module RHC::Commands
class Authorization < Base
summary "Show the authorization tokens for your account"
description <<-DESC
Shows the full list of authorization tokens on your account. You
can add, edit, or delete authorizations with subcommands.
An authorization token grants access to t... |
require 'rails_helper'
RSpec.feature 'Deleting section' do
before do
@admin = create(:admin)
login_as(@admin, scope: :admin)
@section = create(:section)
end
context 'while it has no employees assigned to it' do
it 'should delete this section' do
visit admin_sections_path
expect(page... |
module Exceptions
class GrantPermissionException < StandardError
end
end
|
#
# Tests d'intégration de la partie administration de Test
#
require 'spec_helper'
PISite::set_folder 'test'
describe "Administration de Test" do
before(:all) do
TI::set_offline
TI::as_admin
PISite::set_folder 'test'
end
# === Administration de Test === #
describe "Accessibilité" do
it "Un admin doit po... |
class Cms::CheffsController < Cms::ContentBlockController
skip_before_filter :login_required, :cms_access_required, :only => [:show_details]
def load_dishes
recipe = FoodItem.where(:cheff_id => params[:cheff_id]) if !params[:cheff_id].blank?
@list = {}.tap{ |h| recipe.each{ |c| h[c.id] = [c.meal_info.name... |
# frozen_string_literal: true
class SecureToken
SECRET = Rails.application.secrets.secret_key_base
class << self
def validate!(token)
payload, _header = JWT.decode(token, SECRET)
new(payload.deep_symbolize_keys)
end
def validate(token)
validate!(token)
rescue JWT::DecodeError
... |
require 'nokogiri'
require 'open-uri'
require 'pry'
module Scraper
def self.scrape(link)
all_games = []
doc = Nokogiri::HTML(open(link))
games = doc.css('div.product > .product_info').to_a
games.each do |game|
game_hash = {}
game_hash[:title] = game.children.children.children[0].text
... |
# -*- mode: ruby -*-
# vi: set ft=ruby :
VM_MEMORY = 1024
VM_CPUS = 1
# this is the password you will set for your Splunk admin user
SPLUNK_PASS = "changeme1"
# Splunk home directory
SPLUNK_HOME = "/opt/splunk"
Vagrant.configure("2") do |config|
config.vm.box = "badarsebard/ubuntu-18.04-splunk"
config.vm.d... |
require './to_do_list'
PATH_TO_LISTS = './.to_do_lists/'
EXT = '.tdl'
def load_lists
Dir.mkdir(PATH_TO_LISTS) unless File.exists?(PATH_TO_LISTS)
files = Dir.entries(PATH_TO_LISTS).select { |file| /[A-Za-z\d_-]+.tdl/.match file }
lists = Array.new
files.each_with_index do |file, index|
@extname = File.ext... |
require 'spec_helper'
describe ActiveModel::Phone do
describe 'module methods' do
describe '::default_options' do
it 'should default to empty hash' do
subject.default_options.should eq(validate: true, before_validation: true, default_cc: '1')
end
it 'should persist values' do
... |
cheatsheet do
title 'Cheatset'
docset_file_name 'Cheatset'
keyword 'dash'
source_url 'https://github.com/Kapeli/cheatset'
category do
id 'Generate'
entry do
name '.rdから.docsetを生成'
notes <<-'CODE'
```bash
$ cheatset generate cheatset.rb
# => cheatset.docset が生成される
... |
Pod::Spec.new do |s|
s.name = "Clarifai-Apple-SDK"
s.version = "3.0.3"
s.summary = "Clarifai Apple SDK."
s.description = <<-DESC
The Clarifai Apple SDK allows you to bring powerful A.I. to your mobile apps running on the Apple platform.
... |
require "test_helper"
class ReservationTest < ActiveSupport::TestCase
setup do
@tickets = [
instance_double("Ticket").as_null_object,
instance_double("Ticket").as_null_object,
instance_double("Ticket").as_null_object
]
end
test "calculating the total cost" do
@tickets.each { |ticke... |
require "rails_helper"
feature "Admin panel" do
scenario "Admin can make CRUD actions for question and create answers for him" do
visit root_path
click_on "Write question"
fill_in "question_question_body", with: "2 + 2 = ?"
select("1", :from => "question_score")
select(... |
class CreateClassRoomStudents < ActiveRecord::Migration
def change
create_table :class_room_students do |t|
t.references :class_room, index: true
t.references :student, index: true
t.string :year
t.references :school_branch, index: true
t.references :creator, polymorphic: true, index... |
class Artist < ActiveRecord::Base
has_many :songs
has_many :song_genres, through: :songs
has_many :genres, through: :song_genres
extend Slug::ClassMethods
include Slug::InstanceMethods
end
|
ActiveAdmin.register Municipality do
menu parent: I18n.t('admin.menu.lists')
permit_params :name, :state_id
remove_filter :towns
end
|
class NotesController < ApplicationController
def new
end
def create
@note = Note.new(note_params)
@note.user_id = current_user.id
@note.save
redirect_to track_url(@note.track_id)
end
def destroy
@note = Note.find(params[:id])
@note.destroy
redirect_to track_url(@note.track_id)
end
private
de... |
# Reverse Words
# I worked on this challenge [by myself, with: ].
# This challenge took me [#] hours.
# Pseudocode
# input: String
# output: reverse each word in the sentence.
# create method that inputs a string.
# split the string by spaces into an array
# get the length of the sentence to iterate that many times
... |
require "shrine"
require "shrine/storage/s3"
require "shrine/storage/file_system"
s3_options = {
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
bucket: ENV['AWS_BUCKET'],
region: ENV['AWS_REGION'],
}
if Rails.env.development? || Rails.env.te... |
require 'resource_kit'
module ClinkCloud
class BaseResource < ResourceKit::Resource
# helpful for century link api because the include
# account alias in the url itself
def account_alias
scope.alias
end
def extract_resources_from_links(links, obj, *keys)
links.each do |link|
... |
class FontMaple < Formula
version "5.5"
sha256 "c6467d35e7e35873e358d5bc2c633c0a04f666b8388f57afbf1d4ae7ab14cd1f"
url "https://github.com/subframe7536/Maple-font/releases/download/v#{version}/MapleMono.zip"
desc "Maple Mono"
desc "Nerd Font font with round corners"
homepage "https://github.com/subframe7536/... |
class Cat
def initialize(name, color, age)
@name = name
@color = color
@age = age
end
def meow
"#{@name} says Miaow!"
end
def observe
if ["a", "e", "i", "o", "u"].include?(@color[0])
puts "You see an #{@color} cat"
else
puts "You see a #{@color} cat"
end
end
end
... |
# Note this is not persisted to the database.
class Appeal
include ActiveModel::Model
attr_accessor :organization_campaign_id, :subject, :content
def organization_campaign
OrganizationCampaign.find(@organization_campaign_id)
end
def organization
organization_campaign.organization
end
def send... |
class Recipe < ActiveRecord::Base
has_many :ingredients, :class_name => "IngredientDefinition", :foreign_key => "recipe_id"
has_and_belongs_to_many :tools
has_many :units, :class_name => "IngredientDefinition", :foreign_key => "recipe_id"
has_many :steps
has_many :comments
has_many :eggs
named_scope :good_eggs... |
require 'spec_helper'
describe 'GET api/v1/users.json' do
context 'client is not authenticated' do
it 'should return a status code of 401 (unauthorized)' do
get '/api/v1/users.json'
response.status.should == 401
end
end
context 'client is authenticated' do
before { authenticate_client }
... |
require "mysql-kissmetrics/version"
require "mysql-kissmetrics/km"
module MysqlKissmetrics
require 'dbi'
require 'km'
require 'date'
def self.initialize(profile, username, password, km_key, allowed_history_days = 0)
@allowed_history_days = allowed_history_days
@now = Da... |
module Goauth
class ResultList
attr_reader :items, :pagination
def initialize(json, klass)
@items = json[:items].map { |e| klass.new(e) }.freeze
@pagination = json[:paging].freeze
end
end
end
|
require "byebug"
class Employee
attr_reader :name, :title, :salary
attr_accessor :boss
def initialize(name, title, salary, boss = nil)
@name, @title, @salary, @boss = name, title, salary, boss
end
def boss=(boss)
@boss = boss
@boss.employees << self
end
def bonus(multiplier)
salary * m... |
#
# This is a template vagrant file, you must put it in the project root and
# change the variables project.XXX, but please note
# that there is no support (yet) for an OS other than ubuntu
# You should also edit the last inline provisioning command so that it
# corresponds to the project build proc... |
# frozen_string_literal: true
RspecApiDocumentation.configure do |config|
config.template_path = 'lib'
config.api_name = '6by3 API'
config.format = :api_blueprint
config.request_headers_to_include = ['Authorization', 'Content-Type']
config.response_headers_to_include = ['Content-Type']
config.request_body_... |
require 'spec_helper'
describe Settings do
describe :assignation? do
context "the method name ends with =" do
it "returns true" do
Settings.assignation?("method=").should be_true
end
end
context "the method name does not end with =" do
it "returns false" do
Settings.ass... |
module JackCompiler
module Tokenizer
class Token
MAX_INT = 32767
MIN_INT = 0
attr_reader :kind, :value, :source_location
def initialize(kind, value, source_location:)
@kind = kind
@value = value
@source_location = source_location
end
... |
module Rink
module LineProcessor
# The Line Processor takes partial lines and performs operations on them. This is usually triggered by some special
# character or combination of characters, such as TAB, ARROW UP, ARROW DOWN, and so forth.
#
class Base
attr_reader :source
def initia... |
class Book < ApplicationRecord
has_and_belongs_to_many :authors
validates :title, presence: true
end
|
# frozen_string_literal: true
require 'rails_helper'
describe 'User' do
describe 'As a logged in user when I visit /dashboard' do
before :each do
user = create(:user)
user.token = Token.new(github_token: ENV['GITHUB_API_KEY'])
allow_any_instance_of(ApplicationController).to receive(:current_us... |
# frozen_string_literal: true
module Documents
class AttachmentsController < ApplicationController
def show
render json: attachment
end
def destroy
own_attachment.destroy!
head 200
end
private
def own_attachment
current_user
.available_attachment(document_id... |
class Clue < ActiveRecord::Base
validates_presence_of :description, :longitude, :latitude, :answer
belongs_to :hunt
end
|
class Location < ActiveRecord::Base
belongs_to :shop
has_many :location_menu_item_serving_sizes
has_many :location_menus
validates :name, presence: true, length: {minimum: 5, maximum: 65}
validates :street_address, presence: true
validates :latitude, presence: true
validates :longitude, presence: true
en... |
class ElectionAdministration < ActiveRecord::Base
belongs_to :source
belongs_to :eo, :class_name => 'ElectionOfficial'
belongs_to :ovc, :class_name => 'ElectionOfficial'
has_many :custom_notes, :as => :object
end
|
shared_examples_for "Troles Common Config" do
describe 'config settings' do
describe '#default_orm' do
before :each do
user.troles_config.orm.should == nil
Troles.Config.default_orm = :mongoid
user.troles_config.orm.should == :mongoid
end
end
end
e... |
class RetailerProfilesController < ApplicationController
before_action :set_retailer_profile, only: [:show, :edit, :update, :destroy]
# GET /retailer_profiles
# GET /retailer_profiles.json
def index
@retailer_profiles = RetailerProfile.all
end
# GET /retailer_profiles/1
# GET /retailer_profiles/1.js... |
class Vote < ApplicationRecord
belongs_to :user
belongs_to :review
validates :user_id, :review_id, presence: true
validates_inclusion_of :vote, in: -1..1
end
|
describe Parser::CourtOvertime do
include_context "parser"
let(:file) { file_fixture("sample_court_overtime.csv") }
it "parses a record" do
expect(record[:id]).to eql("010652")
expect(record[:assigned]).to eql("D-4 DCU SQUAD")
end
it "attributes" do
expect(attribution.category).to eql("court_ove... |
require('minitest/autorun')
require_relative('../bear')
require_relative('../fish')
require_relative('../river')
class TestAnimals < MiniTest::Test
def setup
@nemo = Fish.new("Nemo")
@fishy = Fish.new("Fishy")
@eric = Fish.new("Eric")
@fishies = [@nemo, @fishy, @eric]
@river = River.new(@fishie... |
require 'yaml'
require 'digest'
require 'fileutils'
def update_manifest(manifest)
parsed_manifest = YAML.safe_load(manifest)
parsed_manifest['releases'].delete_if { |r| r['name'] == 'kubo' }
if ENV['IS_FINAL']
parsed_manifest['releases'] << kubo_block
else
parsed_manifest['releases'] << kubo_dev_block
... |
describe Payment do
it 'creates' do
expect {
Payment.create_for payment_params
}.to change{ Payment.count }.by 1
end
context 'missing' do
describe 'value' do
let( :value ){ '' }
specify 'fails' do
expect {
Payment.create_for payment_params
}.to_not c... |
class UsersController < ApplicationController
before_action :authorize_request, only: :update
# POST /users
def create
@user = User.new(user_params)
if @user.save
token = encode(user_id: @user.id, email: @user.email)
render json: { user: @user, token: token }, status: :ok
else
rend... |
class AddUrlToPosts < ActiveRecord::Migration
def change
add_column :posts, :url, :string
add_index :posts, :url
Post.initialize_urls
end
end
|
class Guide < ActiveRecord::Base
#-- Associations
belongs_to :course
belongs_to :user
has_many :attachments, as: :attachable, dependent: :destroy
has_many :reports, as: :reportable, dependent: :destroy
has_many :likes, as: :likeable, dependent: :destroy
#-- Attachment attributes
accepts_nested_attribut... |
class Api::Promotions::CakesController < Api::BaseController
skip_before_action :authenticate_user!
before_action :set_cake, only: [:show]
before_action :authenticate_user!, only: [:search_cakes]
def index
@cakes = Cake.order(id: :desc)
.page(params[:page])
.per(params[:per])
render json: ... |
module Campfire
class Campsite
include HTTParty
def initialize (config)
Campsite.base_uri "https://#{config['subdomain']}.campfirenow.com"
Campsite.basic_auth "#{config['api_key']}", "x"
end
def rooms
Campsite.get('/rooms.json')['rooms']
end
def me
Campsite.g... |
#
# Code to help with pagination
#
module Pagination
def paginate(files)
if !files.instance_of? Array; raise "File list must be an array"; end
if files.length == 0; raise "File list cannot be empty"; end
if (files.length % 4) != 0; raise "File list must be divisible by 4"; end
tmp_pdf_files = []
... |
class Genre
extend Concerns::Findable
attr_accessor :name, :song
@@all = []
def initialize(name)
@name = name
@songs = []
end
def songs
@songs
end
def self.all
@@all
end
def self.destroy_all
@@all.clear
end
def save
@@all << self
end
def self.create(name)
genre = Genre.ne... |
require 'rails_helper'
RSpec.describe Message, type: :model do
before(:each) do
@user = build(:user)
end
context "With valid attributes" do
it "should save" do
expect(build(:message, user:@user)).to be_valid
end
end
context "With invalid attributes" do
it "should not save if message ... |
class Alarm < ApplicationModel
belongs_to :sent_user, :class_name => "User", :foreign_key => "sent_user_id"
belongs_to :received_user, :class_name => "User", :foreign_key => "received_user_id"
validates_presence_of :sent_user_id, :received_user_id, :alarm_type
validates_inclusion_of :alarm_type, :in => %w(Follo... |
require 'uuid_helper'
class Coalition < ActiveRecord::Base
include UUIDHelper
nilify_blanks
set_primary_key :uuid
has_many :coalitionships, :primary_key => 'uuid', :foreign_key => 'coalition_uuid'
has_many :parties, :through => :coalitionships
validates :uuid, :uniqueness => true
validates :code, :len... |
# -*- encoding: utf-8 -*-
module Brcobranca
module Remessa
class Transferencia < Brcobranca::Remessa::Pagamento
# Código da Câmara Centralizadora
# Código adotado pela FEBRABAN, para identificar qual Câmara de Centralizadora será responsável pelo processamento dos
# pagamentos.
# Preenche... |
FactoryBot.define do
factory :user, class: User do
# required
email 'user@email.com'
sequence :phone_number do |phone_number|
"#{Random.rand(000000000..999999999)}"
end
sequence :key do |key|
"#{Random.rand(1..1000)}"
end
password 'secret password'
# optional
full_n... |
require 'pathname'
module TheFox
module MBDB
class MBDB
LOOP_MAX = 10000
attr_reader :file_path
attr_reader :records
def initialize(file_path = nil)
@file_path = file_path
@file_h = nil
@offset = 0
@buffer = ''
@records = Array.new
unless file_path.nil?
... |
class FontKarlaTamilInclined < Formula
head "https://github.com/google/fonts.git", verified: "github.com/google/fonts", branch: "main", only_path: "ofl/karlatamilinclined"
desc "Karla Tamil Inclined"
homepage "https://fonts.google.com/specimen/Karla"
def install
(share/"fonts").install "KarlaTamilInclined-B... |
module Vocabulary
class HyperConcept < ApplicationRecord
has_many :relationships, as: :inversable, dependent: :destroy
validates :uri, presence: true
def name
label
end
def api_uri
uri
end
end
end |
require "spec_helper"
describe ApplicationHelper do
describe "#possessive" do
it "adds an 's to Peter" do
helper.possessive("Peter").should == "Peter's"
end
it "only adds an ' to Klaus" do
helper.possessive("Klaus").should == "Klaus'"
end
end
describe "#compare" do
it "returns '... |
class Wireproxy < Formula
desc "Wireguard client that exposes itself as a socks5 proxy or tunnels"
homepage "https://github.com/octeep/wireproxy"
url "https://github.com/octeep/wireproxy/archive/refs/tags/v1.0.5.tar.gz"
sha256 "23eb7939284cfc656459713c40f909e333a26ebce0582bd4dcd75aceb4bb9a08"
license "ISC"
... |
module Mutations
class DisableQuestionAnswer < Mutations::BaseMutation
description 'Hide a potential answer from being displayed on a question.'
argument :question_id, ID, required: true
argument :answer_id, ID, required: true
type Boolean
def resolve(question_id: nil, answ... |
class PaymentRequest < ActiveRecord::Base
#to save payment request parameters
serialize :transaction_parameters
has_many :payments
validates_uniqueness_of :identification_token
before_create :generate_identification_token
before_create :set_is_processed_value
def validate
if transaction_parameters... |
class Workout < ActiveRecord::Base
has_many :exercises, dependent: :destroy
accepts_nested_attributes_for :exercises
end
|
# frozen_string_literal: true
module PYR
VERSION = '0.4.0' # :nodoc:
end
|
module Omniship
class Contact
attr_reader :name,
:attention,
:account,
:phone,
:fax,
:email
def initialize(options={})
@name = options[:name]
@attention = options[:attention]
@phone = options[:phone]
@fax = options[:fax]
@email = options[:email]
end
end
end
|
require 'rails_helper'
describe "#liked_by(user)" do
context "when the post has been liked by user" do
it "selects the post like" do
user = create(:user)
post = create(:post)
post_like = create(:post_like, user_id: user.id, post_id: post.id)
expect(post.liked_by(user)).to eq post_like
... |
require 'hanami/helpers'
require 'hanami/assets'
module Api
class Application < Hanami::Application
configure do
##
# BASIC
#
# Define the root path of this application.
# All paths specified in this configuration are relative to path below.
#
root __dir__
# Rela... |
CarrierWave.configure do |config|
if Rails.env.production? || Rails.env.development?
config.storage = :fog
config.cache_dir = "#{Rails.root}/tmp/"
config.fog_credentials = {
provider: Rails.application.credentials.fog[:provider], # required
aws_access_... |
class CreateSalesOrderItems < ActiveRecord::Migration
def change
create_table :sales_order_items do |t|
t.references :sales_order
t.integer :product_id
t.string :product_name
t.decimal :product_cost
t.decimal :ingredients_cost
t.decimal :packaging_cost
t.decimal :labour_... |
namespace :dev do
desc "Development data for database"
task :populate => :environment do
return unless Rails.env.development?
require 'database_cleaner'
DatabaseCleaner.clean_with(:truncation)
puts 'Creating test user mpalhas@gmail.com/mpalhas'
user = User.create(
name: 'Miguel Palhas',
... |
module Librato
module Metrics
module Taps
class Publisher
SOURCE_NAME_REGEX = /^[-A-Za-z0-9_.]{1,255}$/
@url = nil
@user = nil
@passwd = nil
DEFAULT_BATCH_SIZE = 300
def initialize(opts)
unless !opts[:source] || opts[:source] =~ SOURCE_NAME_REGEX
... |
require './f5'
require 'optparse'
require 'pp'
require 'ostruct'
class Optparser
def self.parse(args)
options = OpenStruct.new
opts = OptionParser.new do |opts|
opts.banner = "Usage: f5_gtm_vs_create.rb [options]"
opts.separator ""
opts.separator "Specific options:"
opt... |
require 'spec_helper'
describe Usergroup do
let(:every_second_wednesday) { Usergroup.new.tap { |it| it.recurring = 'second wednesday 18:30' } }
let(:every_last_wednesday) { Usergroup.new.tap { |it| it.recurring = 'last wednesday 18:30' } }
let(:rughh) { Whitelabel.label_for('hamburg') }
let(:colognerb) { Whi... |
class Tweet < ActiveRecord::Base
validates :text, presence: true, length: { maximum: 140, message: "was interesting, but too long. Please try again." }
belongs_to :user
def find_mentioned_users
users = []
scan_results = self.text.scan(/@[[:alnum:]]+/i) #scan the text for @ followed by any alpha/numeric characte... |
class HomeController < ApplicationController
def index
@home_presenter = HomePresenter.new
render locals: { listed: @home_presenter.listed,
doing: @home_presenter.doing,
done: @home_presenter.done }
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.