2008-09-29 6 views
1

데이터베이스에 XML이 들어있는 'body'라는 필드가 있습니다. 내가 모델에서 만든 방법은 다음과 같습니다개체를 반환하는 모델의 사용자 지정 메서드

def self.get_personal_data_module(person_id) 
    person_module = find_by_person_id(person_id) 
    item_module = Hpricot(person_module.body) 
    personal_info = Array.new 
    personal_info = {:studies => (item_module/"studies").inner_html, 
          :birth_place => (item_module/"birth_place").inner_html, 
          :marrital_status => (item_module/"marrital_status").inner_html} 
    return personal_info 
end 

내가 함수가 배열 대신 개체를 반환합니다. 그래서 Model [: studies] 대신 Module.studies를 사용할 수 있습니다.

감사합니다.
Silviu

p.s 레일 및 루비를 처음 사용합니다. 나는 C 배경을 가지고있다.

답변

4

이것은 비교적 간단합니다. 코드가 하나이기 때문에 Array가 생성됩니다. 당신이 모델 클래스를 피하려면, 당신을

def self.get_personal_data_module(person_id) 
    person_module = find_by_person_id(person_id) 
    item_module = Hpricot(person_module.body) 
    personal_info = PersonalData.new((item_module/"studies").inner_html, 
            (item_module/"birth_place").inner_html, 
            (item_module/"marital_status").innner_html) 
    return personal_info 
end 
+0

매력처럼 작동합니다.) –

2

또는 : 당신이 개체를 반환하고 싶다면, 당신은 같은 것을 할 거라고 :

class PersonalData 
    attr_accessor :studies 
    attr_accessor :birth_place 
    attr_accessor :marital_status 

    def initialize(studies,birth_place,marital_status) 
    @studies = studies 
    @birth_place = birth_place 
    @marital_status = marital_status 
    end 
end 

을 그리고 번역 코드는 같을 것이다

class Hash 
    def to_obj 
    self.inject(Object.new) do |obj, ary| # ary is [:key, "value"] 
     obj.instance_variable_set("@#{ary[0]}", ary[1]) 
     class << obj; self; end.instance_eval do # do this on obj's metaclass 
     attr_reader ary[0].to_sym # add getter method for this ivar 
     end 
     obj # return obj for next iteration 
    end 
    end 
end 

다음 :

h = {:foo => "bar", :baz => "wibble"} 
o = h.to_obj # => #<Object:0x30bf38 @foo="bar", @baz="wibble"> 
o.foo # => "bar" 
o.baz # => "wibble" 
이상한 뭔가를 할 수

마술처럼!

+1

대답 방법보다 논리적으로이 방법을 사용하는 것이 더 좋은 경우를 생각해보십시오. – junkforce

+0

이러한 유형의 솔루션에 대해서는 Ruby를 좋아하기 시작합니다. –

1

약간 다른 점이 있습니다.

클래스 메소드를 사용하여 아이디어를 작성하는 것은 객체 지향 (OO) 관점에서 잘못되었다고 생각합니다.

인스턴스 메소드에서 작동하도록 리팩토링해야합니다.

 
Foobar.get_personal_data_module(the_id) 

당신이

 
Foobar.find_by_person_id(the_id).personal_data_module 

이 악화 보이지만, 사실 할 것 대신하고, 그것은을 사용할 필요가 그런

 
    def personal_data_module 
    item_module = Hpricot(body) 
    { 
     :studies => (item_module/"studies").inner_html, 
     :birth_place => (item_module/"birth_place").inner_html, 
     :marrital_status => (item_module/"marrital_status").inner_html 
    } 
    end 

가, ..., 이잖아 비트 인공, 일반적으로 다른 사람의 개체 에서이 참조 할 수 있습니다, 어디에 실제로 당신이 사람이 개체에 '핸들'을 것입니다, 그래서 그것을 직접 만들 필요가 없을 것입니다.당신은 당신이 외래 키로 person_id로 참조 할 다른 클래스를 가지고있는 경우

예를 들어, 당신은

클래스기구 belongs_to 것 :

다음, 사람 끝을 당신은 조직이 경우, 당신 예

 
organisation.person.personal_information_module 

을 갈 수있는, 내가 알고, 데메테르을 파괴하는, 대리인에 포장하는 것이 좋습니다 것 때문에

 
class Organisation 
    belongs_to :person 

    def personal_info_module 
    person.personal_info_module 
    end 
end 
그리고 컨트롤러 코드에서, 당신은 전혀 출처에 대한 걱정없이

 
organisation.personal_info_module 

을 말할 수 있습니다.

이것은 'personal_data_module'이 실제로 클래스의 속성이며 클래스 메소드를 통해 액세스 할 수있는 속성이 아니기 때문입니다.

그러나 이것은 또한 person_id가이 테이블의 기본 키인지와 같은 몇 가지 질문을 제기합니다. 테이블의 기본 키가 'id'라고 불리는 레거시 상황입니까?

이 경우 ActiveRecord에 대해 말 했나요? 아니면 'find_by_person_id'를 'find'를 쓰고 싶습니까?

+0

http://stackoverflow.com/questions/158482/inject-data-members-to-an-object- 다음으로 관련된 질문입니다. 내가 말했듯이 나는 Ruby에 익숙하지 않고 지금 실험 중이다. 인 퓨에 감사드립니다. 정말 도움이됩니다. –

관련 문제