Skip to content

Instantly share code, notes, and snippets.

View koss-lebedev's full-sized avatar

Konstantin koss-lebedev

View GitHub Profile
class Contact < ActiveRecord::Base
has_dynamic_attributes
# ... other code
end
class ContactAttributeProvider
def initialize(model)
@model = model
end
def call
[
ActiveDynamic::AttributeDefinition.new('age', datatype: ActiveDynamic::DataType::Integer, default_value: 18),
ActiveDynamic::AttributeDefinition.new('description')
class ContactAttributeProvider
def initialize(model)
@model = model
end
def call
ContactAttribute.all.map do |attr|
ActiveDynamic::AttributeDefinition.new(
attr.name, datatype: attr.datatype,
required: attr.required?
contact = Contact.new
# first_name is a regular attribute mapped to
# a column in contacts table
contact.first_name = 'John'
# age attribute was added dynamically
contact.age = 27
contact.save
def dynamic_attribute_inputs(form, model)
inputs = model.dynamic_attributes.map do |attr|
options = {
label: attr.display_name,
as: datatype_mapping(attr.datatype)
}
form.input attr.name, options
end
safe_join inputs
<%= simple_form_for(contact) do |f| %>
... code omitted
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= dynamic_attribute_inputs(f, contact) %>
<%= f.button :submit %>
<% end %>
def contact_params
params.require(:contact).permit(
*Contact.new.dynamic_attributes.map(&:name), :first_name)
end
config.provider_class = CustomAttributeResolver
import React, { FunctionComponent } from 'react'
type Props = {
posts: readonly RedditPost[]
subreddit: string
}
const Posts: FunctionComponent<Props> = ({ posts, subreddit }) => (
<div>
<h1>Posts in "{subreddit}"</h1>
/*
* ERROR: Property 'getInitialProps' does not exist on type 'FunctionComponent<Props>'.
*/
Posts.getInitialProps = async () => {
const subreddit = 'typescript'
const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`)
const result = await response.json() as RedditResult
return {
subreddit,