1

Is is possible to create a custom model attribute and get its value included by default, whenever that model is called?

I have a model named Video. It has an attribute named name. It contains the name of the video sample-video.mp4. I want to create two custom attributes named iphone_url and android_url for model.

Both attributes will have different urls concatenated with name. So, iphone_url will have http://link1/+name+/playlist.m3u8 where as android_url will have http://link2/+name

Is it possible that whenevr i call that model, both attributes are automatically added(in JSON response)?

I tried solutions mentioned here.

I was able to add custom attributes by using attr_accessor, but their value is always null. May be because their value needs to be set manually first.

So how to do this?

Edit: Currently, i'm doing like this:

videos = Array.new

# Dirty, but works      
Video.all.each do |video|
    video = video.attributes

    wowza_server = "X.X.X.X:XXXX/AppName/"
    custom_attributes = {:wowza_urls => {:ios => "http://"+wowza_server+"mp4:"+video[:name])+"/playlist.m3u8", :android => "rtsp://"+wowza_server+video[:name])}}

    videos << video.merge(custom_attributes)
end

render :json => videos, status: :ok
Community
  • 1
  • 1
Kanav
  • 2,695
  • 8
  • 34
  • 56

1 Answers1

0

This is really what jbuilder was made for.

Jbuilder gives you a simple DSL for declaring JSON structures that beats massaging giant hash structures.

You're starting to massage a giant hash structure.

I'm assuming this is an index view, in which case it look something like this:

json.array! @videos do |video|
  json.my_field video.my_field
  json.iphone_url video.iphone_url
  json.android_url video.android_url
end

On your app/model/video.rb

class Video
  def iphone_url
    "some_url_to_build"
  end
  ...
end
Anthony
  • 15,435
  • 4
  • 39
  • 69