text stringlengths 10 2.61M |
|---|
class CreateYears < ActiveRecord::Migration[5.0]
def change
create_table :years do |t|
t.string :description
t.date :begin
t.date :end
t.decimal :starting_balance, precision: 10, scale: 2, default: 0.00
t.boolean :closed, default: false
t.boolean :ordinary, default: true
... |
class ImageRequest < ApplicationRecord
has_one :image_group, through: :image
belongs_to :image, counter_cache: :views_count
delegate :file, to: :image
end
|
require './spec/spec_helper'
describe OmniSearch::StringDistance::WordDistance do
let(:the_class) {OmniSearch::StringDistance::WordDistance}
subject { the_class.new('query', 'reference') }
describe 'word score' do
def score(query, reference)
the_class.score(query, reference)
end
let(:null_mat... |
describe Catalog::Notify do
let(:subject) { described_class.new(klass, id, payload) }
describe "#process" do
context "when the class is not an acceptable notification class" do
context "when the class is an order item" do
let(:klass) { "order_item" }
let(:order) { create(:order) }
... |
class Change < ActiveRecord::Migration[5.0]
def change
change_column :estates, :square_feet, :integer
end
end
|
class CocktailsController < ApplicationController
# shows all cocktails
def index
@cocktails = Cocktail.all
end
# shows one cocktail
def show
@cocktail = Cocktail.find(params[:id])
end
def new
@cocktail = Cocktail.new
end
def create
@cocktail = Cocktail.new(cocktail_params)
if @c... |
class Product < ActiveRecord::Base
include ActionView::Helpers::NumberHelper
include PgSearch
multisearchable :against => [:name]
pg_search_scope :search_by_keyword,
:against => :name,
:using => {
:tsearch => {
:prefix => true # mat... |
class RenameCachedSlugToSlug < ActiveRecord::Migration
def change
%w(code languages locations portfolios posts quotes sources tags).each do |table|
rename_column table, :cached_slug, :slug
end
end
end
|
require "rails_helper"
describe SchedulePresenter do
describe '#week' do
it 'returns humanized day names with values returned by #day method' do
schedule = Schedule.create(tuesday: ['8'])
subject = SchedulePresenter.new(schedule)
allow(subject).to receive(:day) do |value|
value << 1
... |
require 'spec_helper'
describe BuBus::Client do
describe "buses" do
it "returns a collection of bus objects" do
VCR.use_cassette("bus_positions_sample") do
client = BuBus::Client.new
buses_array = client.buses
expect(buses_array.is_a?(Array)).to eq(true)
expect(buses_array.l... |
class CreateTasks < ActiveRecord::Migration[6.1]
def change
create_table :tasks do |t|
t.string :name_task
t.bigint :subject_id
t.timestamps
end
add_foreign_key :tasks, :subjects
end
end
|
class Goddess < ActiveRecord::Base
belongs_to :chakra
validates_presence_of :chakra, :name, :number, :description, :modern_energy, :do_this
validates_numericality_of :number, :only_integer => true
end
|
json.array!(@promos) do |promo|
json.extract! promo, :id, :nome, :dataInicio, :dataFim, :activo, :tipoPromo, :descricao, :Id_Loja
json.url promo_url(promo, format: :json)
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
# -*- encoding : utf-8 -*-
class CreateZakons < ActiveRecord::Migration
def change
create_table :zakons do |t|
t.text :name
t.text :link
t.boolean :visible
t.timestamps
end
end
end
|
class ProductsController < ApplicationController
before_action :set_product, except: [:index, :new, :create, :search, :get_category_children, :get_category_grandchildren]
def index
@products = Product.includes(:images).limit(4).order('created_at DESC')
# includesメソッドで記述する際には、親モデルに対して子モデルの命名は複数形で記述する。
... |
class Airplane
attr_reader :position, :flying, :fuel, :speed
def initialize(x:, y:, flying:, speed:, fuel:)
@position={x: x, y: y}
@flying= flying
@speed= speed
@fuel= fuel
end
def set_speed(speed)
@speed = [[0, speed].max, 10].min
end
def accelarate
@speed += 2
end
de... |
FactoryBot.define do
factory :drug_stock do
id { SecureRandom.uuid }
association :facility
region { facility.region }
association :user
association :protocol_drug
for_end_of_month { Date.today.end_of_month }
in_stock { rand(1..1000) }
received { rand(1..1000) }
redistributed { rand... |
class AddUserRefToApiKeys < ActiveRecord::Migration[5.1]
def change
add_reference :api_keys, :user, index: true
end
end
|
module Prov
def prov(name,&block)
klass=Command.const_set(name.to_s.capitalize,Class.new(Command))
klass.send(:define_method,:do_description,block)
end
module_function :prov
class Command
include RDF
include Statemented
def initialize(prov_block,*args)
@prov_block=prov_block
@tr... |
require 'locus/collections/components'
require 'locus/collections/sites'
module Locus
module Collections
def self.classes
[
Locus::Components,
Locus::Sites
]
end
def self.find_class(name)
self.classes.find(Proc.new { Locus::Collection }) { |c| c.collection_name ==... |
# A class, like in java
class Bug
#Constructor
def initialize( max ) #initialize max to parameter
@number = 0 #the current number of bugs
@max = max #the max number of bugs before the programmer gives up
@seed = Random.new_seed #The seed we use so that the file and stdout are the same
... |
class CreateMachineTranslationDynamicAnnotation < ActiveRecord::Migration[4.2]
require 'sample_data'
include SampleData
def change
ft = create_field_type(field_type: 'json', label: 'JSON structure')
at = create_annotation_type annotation_type: 'mt', label: 'Machine translation'
create_field_instance ... |
class Indication < ApplicationRecord
has_many :rules
default_scope { where(is_active: true) }
end
|
class AddFlagToMeters < ActiveRecord::Migration[5.0]
def change
add_column :meters, :f, :boolean, column_options: { null: false, default: true }
add_column :mpoints, :f, :boolean, column_options: { null: false, default: true }
add_column :companies, :f, :boolean, column_options: { null: false, default: tr... |
class Post < ActiveRecord::Base
has_many :comments, :dependent => :destroy
belongs_to :blog_category
scope :published, lambda {
self.where(["is_published = ? AND published_at < ?", true, Time.now])
}
scope :last_posts, lambda { |max_post|
self.where(['published_at <= ?', Time.now]).order('published... |
class AddWeekNoToVersionProgresses < ActiveRecord::Migration
def self.up
add_column :version_progresses, :week_no, :integer
end
def self.down
remove_column :version_progresses, :week_no
end
end
|
class ApplicationMailer < ActionMailer::Base
default from: 'no-reply@zineya.com'
layout 'mailer'
def send_feedback(feedback)
@feedback = feedback
mail(:to => "fraz.ahsan17@gmail.com", :subject => "Zineya Feedback")
end
end
|
require 'simplecov'
SimpleCov.start
# Configure Rails Environment
ENV['RAILS_ENV'] = 'test'
require File.expand_path('../dummy/config/environment.rb', __FILE__)
require 'rails/test_help'
require 'mocha/minitest'
Rails.backtrace_cleaner.remove_silencers!
# Load support files
Dir["#{File.dirname(__FILE__)}/support/*... |
class AddLikesCountToTopics < ActiveRecord::Migration
def up
add_column :topics, :likes_count, :integer
Topic.all.each do |topic|
Topic.reset_counters(topic.id, :likes)
end
end
def down
remove_column :topics, :likes_count
end
end
|
class ReviewGuidesController < ApplicationController
before_action :set_review_guide, only: [:show, :edit, :update, :destroy]
before_action :set_guide
before_action :authenticate_visitor!
def new_review_guide
@review_guide = ReviewGuide.new
end
def edit
end
def create_review_guide
@review_gui... |
# Author: Martinique Dolce
# Course: Flatiron School 2020, November 9 - 20201, April 2021
# Contact: me@martidolce.com | https://modis.martidolce.com
#
# Objectives
# Define new Ruby classes with the class keyword.
# Instantiate instances of a class.
# Overview
# This lab is all about defining classes and instantiating... |
class MessagesController < ApplicationController
before_action :require_login
before_action :set_message, only: [:destroy] # :edit, :update,
before_action :check_and_prepare_reply, only: [:reply_new, :reply_create]
# GET /messages
# GET /messages.json
def index
@is_thread = false
if params["view"] ... |
class CreateBlogsSongs < ActiveRecord::Migration
def change
create_table :blogs_songs, :id => false do |t|
t.references :blog, :song
end
end
end
|
class TicTacToeCLI
def start_game
puts 'Welcome to Tic Tac Toe.'
puts 'Would you like to play a 0, 1 or 2 player game?'
puts "Type 0 for: COMPUTER vs COMPUTER"
puts "Type 1 for: HUMAN vs COMPUTER"
puts "Type 2 for: HUMAN VS HUMAN"
input_game_type = gets.strip
if input_game_type == '0'
... |
module HasCounterOn
module CounterMethods
private
def has_counter_on_after_create
self.has_counter_on_options.each do |get_counter, foreign_key, conditions|
next unless satisfy_present?(conditions: conditions)
association_id = send(foreign_key)
counter = get_counter.call(id: as... |
Rails.application.routes.draw do
root 'products#index_9'
category_constraints = {
category: /(air)|(tropical)|(succulents)|(cacti)|(herbs)|(trees)|(planters)/
}
resources :merchants, except: [:new, :destroy, :edit, :update] do
get 'orders', to: 'orders#index'
patch 'orders/:id/ship', to: 'orders#ship', a... |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :sm, :class => 'Sms' do
message_id 1
sms_id 1
phone "MyString"
mes "MyText"
phone_to "MyString"
sent "2013-12-09 12:08:22"
recieved "2013-12-09 12:08:22"
md5 "MyString"
sha1 "MyStrin... |
class Topic < ActiveRecord::Base
has_many :subtopics
has_many :podcasts, through: :podcasts_topics
has_many :podcasts_topics
end |
require "test_helper"
describe MoviesController do
describe "index" do
it "is a real working route and returns JSON" do
get movies_path
expect(response.header['Content-Type']).must_include 'json'
must_respond_with :success
end
it "returns an Array" do
get movies_path
bod... |
require "metacrunch/hash"
require "metacrunch/transformator/transformation/step"
require_relative "../aleph_mab_normalization"
class Metacrunch::ULBD::Transformations::AlephMabNormalization::AddSecondaryFormPublisher < Metacrunch::Transformator::Transformation::Step
def call
target ? Metacrunch::Hash.add(target,... |
#
# Author:: Edmund Haselwanter (<office@iteh.at>)
# Copyright:: Copyright (c) 2011 Edmund Haselwanter
# License:: Apache License, Version 2.0
#
# 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
... |
require 'spec_helper'
describe Valet::Option::Switch do
it_behaves_like "a common option"
subject(:opt) { Option::Switch.new(:verbose) }
its(:default) { should be_false }
its(:value) { should be_false }
describe "attributes" do
it "can be given a new default 'true'" do
opt.default = true
... |
require './database_config/database_config.rb'
require './connection_adapter/postgres_adapter.rb'
require './connection_adapter/postgres_connection.rb'
class DatabaseInitiator
DB_MAPPER = {
'postgresql' => { connection_class: ::PostgresConnection, adapter_class: ::PostgresAdapter }
}
def initialize(env_name... |
class AgreementChangesController < ApplicationController
load_and_authorize_resource
def new
@agreement = Agreement.find(params["agreement_id"])
respond_to do |format|
format.html
format.json { render json: @agreement_change }
end
end
def create
@agreement = Agreement.find(params... |
class CatRentalRequestsController < ApplicationController
def index
@cats = Cat.all
@cat_rentals = CatRentalRequest.all
end
def show
render :show
end
def new
@cats = Cat.all
@cat_rental = CatRentalRequest.new
end
def create
@cat_rental = CatRentalRequest.new(cat_rental_params)
... |
class Api::VotationsController < ApplicationController
def update
@user = current_user
@group = Group.find(params["group"])
@event = Event.find(params["event"])
@appointments = @event.appointments
if !@event.deadlinePassed?
@appointments.each do |appointment|
votation = appointmen... |
class EatSubcategory < ActiveRecord::Base
belongs_to :eat_category
has_many :eat_category_decisions
has_many :eat_decisions, through: :eat_category_decisions
def self.list
order('name ASC').pluck("name AS subcategory")
end
end
|
class Profile < ApplicationRecord
validates :phone, length: { is: 14 }
belongs_to :user
end
|
require 'rubygems'
require 'json'
require 'net/http'
require_relative 'interaction'
# to represent a page of information on the internet
class WebPage
attr_reader :url, :interactions
protected :url, :interactions
def initialize(url)
url =~ /^#{URI::regexp}$/ ? @url = url : raise('Not a valid URL: ' + url)
end... |
module Kuhsaft
class VideoBrick < Brick
YOUTUBE = 'youtube'
VIMEO = 'vimeo'
EXTERNAL = 'external'
validates :any_source, presence: true
# a video id, an embed code or a link to a video is required
def any_source
embed_src.presence || href.presence
end
def self.source_types
... |
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :validatable, :confirmable, :lockable, :timeoutable, :omniauthable, :registerable, :recoverable
devise :database_authenticatable, :rememberable, :trackable, :registerable
has_many :products, dependent: :destroy
has_many... |
require 'pry'
require 'spec_helper'
require 'docproof'
module Docproof
describe PaymentProcessor do
let(:options) { {} }
let(:processor) { described_class.new(options) }
describe '#bitcoin_address' do
subject { processor.bitcoin_address }
context 'using pay_address' do
let(:options)... |
class Food < ActiveRecord::Base
extend FriendlyId
belongs_to :food_group
validates_presence_of :name
mount_uploader :picture, PictureUploader
friendly_id :name
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
source 'https://rubygems.org'
# Declare your gem's dependencies in frank.gemspec.
# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.
gemspec
# Declare any dependencies that are still in development here instead of in
# y... |
# 数据统计接口模块
module EricWeixin::AnalyzeData
# 自动去微信服务器拉取当日之前的统计模块的数据.
# ===参数说明
# * weixin_public_account_id # 微信公众号ID
# ===调用实例
# ::EricWeixin::AnalyzeData::InterfaceData.auto_get_and_save_data_from_weixin 1
def self.auto_get_and_save_data_from_weixin weixin_public_account_id
::EricWeixin::Report::UserD... |
require 'lab42/tmux/auto_import'
require 'lab42/core/hash'
module VimPlugin
def vim_command command, params
send_keys ":#{command} #{params}"
end
def vim_new_window name, **options
new_window name do
send_keys "vi #{__vim_dir options}"
__vim_source options
__vim_colorscheme options
... |
def hipsterfy(word)
reversed = word.reverse
vowels = "aeiou"
reversed.each_char.with_index do |char, idx|
if vowels.include?(char)
reversed[idx] = ""
break
end
end
hipsterfied = reversed.reverse
hipsterfied
end
def vowel_counts(str)
counts = Hash.new(0)
vowels = "aeiou"
str.each... |
module DublinBikes
class StationStatus
attr_reader :available_bikes, :free_spaces, :total_capacity, :updated_at
def initialize(station)
@available_bikes = station.available
@free_spaces = station.free
@total_capacity = station.total
@open = station.open == 1
@accepts_credit_card... |
# 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... |
class UsersController < ApplicationController
def index
# logger.info "Index User info"
# Rails.logger.info "sample text"
# @user=User.find(:first, :conditions=>["account = ?", params[:account]])
end
def new
logger.info "Index the userdetails"
@user=User.new
end
def create
... |
class Admin::BaseController < ApplicationController
before_action :authenticate_user!
before_action :_check_admin_user
def _check_admin_user
return if current_user.superadmin?
Notify.message('_check_admin_user', current_user: current_user)
redirect_to root_path, alert: t('only_for_superadmin')
end... |
Pod::Spec.new do |s|
s.name = "IOS_CapitalCloudSDK_Library"
s.version = "1.0.13"
s.summary = "ios player lib for capitalcloud client."
s.description = <<-DESC
Ios player lib for capitalcloud client.
DESC
s.homepage = "https://github.com/Capi... |
require 'pp'
def random_number(distribution)
r = rand # Random number in [0,1]
return 1 if r > distribution[0]
return 0
end
def generate_tuples(n, model)
tuples = []
(0..(n-1)).each do |i|
tuple = {}
model.nodes.each do |node|
enabled = true
node.parents.each do |parent|
enabled ... |
require 'easy_extensions/easy_sync/easy_sync'
require 'net/http'
require 'nokogiri'
class EasySyncXml < EasySync
def initialize(options)
@uri = URI(options[:url])
@auth = options[:auth]
@ssl = options[:ssl]
@items_xpath = options[:items_xpath]
@xml_items = []
@items = []
super
end
... |
# frozen_string_literal: true
require 'sinatra/activerecord'
require_relative '../errors/unauthorized_error.rb'
require_relative '../orm/movie_piles.rb'
require_relative '../services/movie_service.rb'
# model to retrieve movie information to show as movie pile
class MoviePileOrmModel
def create(data)
movie_pile... |
class InterestEraserPage
include PageObject
include DataMagic
include FooterPanel
include HeaderPanel
page_url FigNewton.cos_url_prefix + FigNewton.cos_url_app_context + '/#/accounts/offers/interesteraser'
# Active Offers
img(:prod_image, :id => 'productImage')
h3(:prod_name, :id => 'productName')
... |
require 'rspec'
require 'jievro/parser/string_parser'
require 'jievro/ast/node'
unless defined? bug_number
def bug_number
false
end
end
unless defined? source
def source
raise Exception, 'Source code not provided'
end
end
unless defined? expected_tokens
def expected_tokens
raise Exception, 'Exp... |
require 'active_record/base'
module RTree
module ActsAsRTree
extend ActiveSupport::Concern
module ClassMethods
def acts_as_rtree(options = {})
configuration = {
:foreign_key => "parent_id",
:order => nil,
:position_column => nil,
:counter_cache =>... |
module Api
module V2
class BaseResource < JSONAPI::Resource
# Data should be always scoped by workspace
def self.workspaces(options = {})
user = options.dig(:context, :current_user)
teams = Team.none
if user
teams = user.teams
elsif options.dig(:context, :curr... |
json.array!(@wines) do |wine|
json.( wine, :id, :name )
end |
json.array!(@scaffilds) do |scaffild|
json.extract! scaffild, :Micropost, :content, :user_id
json.url scaffild_url(scaffild, format: :json)
end |
FactoryGirl.define do
factory :training do
start_date "2016-06-22 17:36:03"
end_date "2016-06-22 17:36:03"
title "MyString"
description "MyString"
capacity 1
end
end
|
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Ch... |
require 'spec_helper'
RSpec.describe Smite::Friend do
let(:player) { Smite::Game.player('adapting') }
let(:smite_obj) { player.friends[0] }
describe '#to_player' do
it 'returns a Smite::Player instance of this friend' do
expect(smite_obj.to_player.class).to eq(Smite::Player)
end
end
it_beh... |
require 'spec_helper'
describe Faces do
let(:faces) { Faces.new(origin: [0, 0, 0], dimensions: [4, 4, 4])}
describe '#collection' do
it 'shows the collection of face values' do
expect(faces.collection.length).to eq(3)
expect(faces.collection).to match_array([[0, 4], [0, 4], [0, 4]])
end
end
... |
module Admin
class MenuDetailsController < AdminBaseController
def create
@menu = Menu.find_by id: params[:menu_id]
@menudetail = @menu.picks.build menudetails_params
if @menudetail.save
flash[:success] = t ".created"
else
flash[:danger] = t ".not_created"
end
r... |
# frozen_string_literal: true
class CreateJoinTableCategoryNumberParameter < ActiveRecord::Migration[5.2]
def change
create_table :number_filters, id: false do |table|
table.integer :category_id, null: false
table.integer :number_parameter_id, null: false
end
end
end
|
#!/usr/bin/env ruby -wKU
# This is an example of the Composite pattern.
#
# It enables you to represent an organization as tree structures,
# with departments, subdepartments, and people as nodes.
#
# Note that people are leaf nodes in this structure,
# since their records cannot enclose other records.
#
# Use RSpec... |
module Ricer::Plugins::Auth
class Servermod < Ricer::Plugin
trigger_is :mods
has_usage :execute_change_for_user, '<user> <permission>'
def execute_change_for_user(user, change_permission)
return rplyp :err_unregistered unless user.registered?
old_permission = user.permission
... |
require 'rails_helper'
describe Api::V1::Posts do
describe 'API Create posts' do
let(:user) { create :user }
let(:login) { Faker::Name.name }
let(:title) { Faker::Hipster.sentence }
let(:description) { Faker::Hipster.paragraph }
let(:params) { { login: login, title: title, description: descripti... |
class Group < ApplicationRecord
has_many :users
belongs_to :company
end
|
class Player
end
class Player
def initialize(nama)
@nama = nama
@blood = 100
@manna = 40
end
# definisi nama, jadi entar pas buat object namanya bisa dipanggil dengan cara player.nama, liat inisialisasi objek
def nama
puts "nama : #{@nama}"
puts "blood : #{@blo... |
class Hobbit
attr_accessor :name, :age, :disposition, :is_adult, :is_old, :has_ring
attr_reader :short
def initialize(name, disposition = "homebody", age = 0, has_ring = false)
@name = name
@disposition = disposition
@age = age
@is_adult = false
@is_old = false
@short = true
end
def ... |
require_relative 'node'
require 'pry'
require 'benchmark'
class LinkedList
attr_accessor :head
attr_accessor :tail
def initialize
@head = nil
@tail = nil
end
# This method creates a new `Node` using `data`, and inserts it at the end of the list.
def add_to_tail(node)
new_node = node
if no... |
# == Schema Information
#
# Table name: projects
#
# id :integer not null, primary key
# subject_id :integer
# name :string
# explanation_text :text
# explanation_video_url :string
# published :boolean
# row :integer
# cr... |
require "ssh/shell-process"
#
# Run a command via SSH with agent forwarding enabled. The following
# options are available:
#
# <tt>:logger</tt>:: Save logs with the specified logger [nil]
# <tt>:verbose</tt>:: Be verbose [nil]
# <tt>:dry_run</tt>:: Print the commands that would be executed, but do not execute them.... |
class Dogsitter < ApplicationRecord
belongs_to :city
has_many :strolls
has_many :dogs, through: :strolls
end
|
# Returns a value (MB) that might be suitable to set the MAX_HEAP_SIZE.
# See [Tuning Java resources]
# (https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/ops_tune_jvm_c.html)
# for more details.
#
# @return [integer] max(min(1/2 ram, 1024), min(1/4 ram, 8192))
# @see cassandracmsheapnewsize
# @see cassan... |
class Nakkitype < ActiveRecord::Base
belongs_to :party
has_many :nakkis, :dependent => :delete_all
belongs_to :nakkitype_info
validates :party_id, :presence => true
validates :nakkitype_info_id, :presence => true
end
|
# -*- encoding : utf-8 -*-
APP_ROOT = "/home/admin/apps/rollout_service/current"
puts "AppPath: #{APP_ROOT}"
worker_processes 1
working_directory APP_ROOT
listen 'unix://home/admin/apps/rollout_service/shared/var/rollout_service.socket', backlog: 512
listen 9876, tcp_nopush: true
timeout 120
pid "var/unicorn.pid"
std... |
class Product < ActiveRecord::Base
# has_and_belongs_to_many :catagories
has_many :category_products
has_many :categories, through: :category_products
accepts_nested_attributes_for :category_products
def possible_categories
Category.all.map {|category| category.kind}
end
end
|
class CreateProsumersUsers < ActiveRecord::Migration
def self.up
create_table :prosumers_users, id: false do |t|
t.integer :prosumer_id
t.integer :user_id
end
add_index :prosumers_users, [:prosumer_id, :user_id]
end
def self.down
drop_table :prosumers_users
end
end
|
class User < ApplicationRecord
has_many :questions, dependent: :destroy
has_many :answers, dependent: :destroy
has_secure_password
has_one_attached :image
end
|
class SightingSerializer
include FastJsonapi::ObjectSerializer
attributes :created_at
belongs_to :bird
belongs_to :location
# @sighting.to_json(:include => {:bird => {:only =>[:name, :species]}, :location => {:only =>[:latitude, :longitude]}}, :except => [:updated_at])
end
|
require 'rails_helper'
describe "Items API" do
context "Items Endpoint" do
it "can send a list of items" do
item = create_list(:item, 3).first
get "/api/v1/items"
expect(response).to be_success
items = JSON.parse(response.body)
expect(items.count).to eq(3)
end
it "can s... |
require 'test_helper'
class TestProcNetBase < Test::Unit::TestCase
def setup
@tcp = ProcNet::Tcp.new
end
def test_hex_to_ip
assert_equal '98.138.253.109', ProcNet::Tcp.hex2ip('628AFD6D')
end
def test_hex_to_port
assert_equal "22", ProcNet::Tcp.hex2port('0016')
end
def test_read
table = ... |
require "swagger_helper"
describe "Users v4 API", swagger_doc: "v4/swagger.json" do
path "/users/find" do
post "Find a existing user" do
tags "User"
parameter name: :phone_number, in: :body, schema: Api::V4::Schema.user_find_request
let(:known_phone_number) { Faker::PhoneNumber.phone_number }
... |
Dir.glob("#{File.dirname(__FILE__)}/cloudformula/*.rb") { |file| require file }
module CloudFormula
class << self # class methods
# Creates a new CloudFormula::Template object.
# @see CloudFormula::Template.initialize
def template(source = '', parameters = {})
Template.new(source, parameters)
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.